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

六月ゝ 毕业季﹏ 提交于 2019-12-01 06:33:29

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;

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

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.

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