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

天涯浪子 提交于 2019-12-04 01:36:53

问题


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!


回答1:


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;



回答2:


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




回答3:


Tuomas Pelkonen already presented the gettimeofday method that allows to get times with a resolution to the microsecond.

In his example he goes on to convert to double. I personally have wrapped the timeval struct into a class of my own that keep the counts into seconds and microseconds as integers and handle the add and minus operations correctly.

I prefer to keep integers (with exact maths) rather than get to floating points numbers and all their woes when I can.



来源:https://stackoverflow.com/questions/2533774/measuring-execution-time-of-a-call-to-system-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!