Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring execution time of a call to system() in C++

Tags:

c++

linux

timing

I have found some code on measuring execution time here http://www.dreamincode.net/forums/index.php?showtopic=24685

However, it does not seem to work for calls to system(). I imagine this is because the execution jumps out of the current process.

clock_t begin=clock();

system(something);

clock_t end=clock();
cout<<"Execution time: "<<diffclock(end,begin)<<" s."<<endl;

Then

double diffclock(clock_t clock1,clock_t clock2)
{
    double diffticks=clock1-clock2;
    double diffms=(diffticks)/(CLOCKS_PER_SEC);
    return diffms;
}

However this always returns 0 seconds... Is there another method that will work?

Also, this is in Linux.

Edit: Also, just to add, the execution time is in the order of hours. So accuracy is not really an issue.

Thanks!

like image 539
jm1234567890 Avatar asked Dec 08 '22 03:12

jm1234567890


2 Answers

Have you considered using gettimeofday?

struct timeval tv;
struct timeval start_tv;

gettimeofday(&start_tv, NULL);

system(something);

double elapsed = 0.0;

gettimeofday(&tv, NULL);
elapsed = (tv.tv_sec - start_tv.tv_sec) +
  (tv.tv_usec - start_tv.tv_usec) / 1000000.0;
like image 100
Tuomas Pelkonen Avatar answered Dec 21 '22 00:12

Tuomas Pelkonen


Unfortunately clock() only has one second resolution on Linux (even though it returns the time in units of microseconds).

Many people use gettimeofday() for benchmarking, but that measures elapsed time - not time used by this process/thread - so isn't ideal. Obviously if your system is more or less idle and your tests are quite long then you can average the results. Normally less of a problem but still worth knowing about is that the time returned by gettimeofday() is non-monatonic - it can jump around a bit e.g. when your system first connects to an NTP time server.

The best thing to use for benchmarking is clock_gettime() with whichever option is most suitable for your task.

  • CLOCK_THREAD_CPUTIME_ID - Thread-specific CPU-time clock.
  • CLOCK_PROCESS_CPUTIME_ID - High-resolution per-process timer from the CPU.
  • CLOCK_MONOTONIC - Represents monotonic time since some unspecified starting point.
  • CLOCK_REALTIME - System-wide realtime clock.

NOTE though, that not all options are supported on all Linux platforms - except clock_gettime(CLOCK_REALTIME) which is equivalent to gettimeofday().

Useful link: Profiling Code Using clock_gettime

like image 40
Dipstick Avatar answered Dec 21 '22 00:12

Dipstick