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

后端 未结 3 1909
甜味超标
甜味超标 2021-01-14 02:46

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 sy

相关标签:
3条回答
  • 2021-01-14 03:34

    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;
    
    0 讨论(0)
  • 2021-01-14 03:35

    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

    0 讨论(0)
  • 2021-01-14 03:42

    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.

    0 讨论(0)
提交回复
热议问题