Software Design

Design de software em C, C++, Java, etc…

C++ Class to Measure execution time of a method

Here is a simple class that can be used to measure the execution time of a method or group of methods. Alternatively it can be used as a measure of the lifecycle of an object, it’s all about scope.

That’s the class.

#include <time.h>

class TimeSpan {
		string name;
		timespec start;
		timespec end;
		TimeSpan(const string &n) : name(n) {
			clock_gettime(CLOCK_REALTIME, &start);
		~TimeSpan() {
			clock_gettime(CLOCK_REALTIME, &end);
			cout << name << " elapsed: " << end.tv_sec-start.tv_sec <<
				" seconds + "<< end.tv_nsec - start.tv_nsec <<
				" nanoseconds" << endl;

According to clock_gettime’s man page, the first parameter must be one of the following:

CLOCK_REALTIME: System-wide realtime clock. Setting this clock requires appropriate privileges.
CLOCK_MONOTONIC: Clock that cannot be set and represents monotonic time since some unspecified starting point.
CLOCK_PROCESS_CPUTIME_ID: High-resolution per-process timer from the CPU.
CLOCK_THREAD_CPUTIME_ID: Thread-specific CPU-time clock.

The usage of this class is quite simple. For example, you have a method that calculates a fibonacci:

int Math::fib(int x) {

  TimeSpan ts("Math::fib");
  //... your code here... //


You’ll probably need to link your program with librt.

The result should be anything like:
Math::fib elapsed: 0s + 13217 nanoseconds

This mean that the fib method spent 13217 seconds ( or 13.21 microseconds, or 0,01 milliseconds )

This code is linux specific, each operating system has it’s own mechanism to get RTC information. The clock_gettime’s man page also add the following note:

NOTE for SMP systems

The CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID clocks are realized on many platforms using timers from the CPUs (TSC on i386, AR.ITC on Itanium). These registers may differ between CPUs and as a consequence these clocks may return bogus results if a process is migrated to another CPU.

Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do

Você está comentando utilizando sua conta Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s


Publicado às outubro 26, 2011 por em C++, Linux, Profiling, Unix e marcado , , , .
%d blogueiros gostam disto: