Measuring system call execution time () in C ++

I found code for measuring runtime here http://www.dreamincode.net/forums/index.php?showtopic=24685

However, it does not work for calls in system (). I suppose this is because 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 any other way that will work?

It is also on Linux.

Edit: also, to add, the runtime is of the order of an hour. Therefore, accuracy is not a problem.

Thanks!

+4
source share
3 answers

Do you find 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; 
+9
source

Unfortunately, clock () has only one second resolution on Linux (although it returns time in units of microseconds).

Many people use gettimeofday () for benchmarking, but this means that elapsed time - not the time used by this process / thread - is not ideal. Obviously, if your system is more or less idle, and your tests are quite long, you can average the results. Usually less of a problem, but it's worth knowing that the time returned by gettimeofday () is non-monotonous - it can jump a bit, for example. when your system first connects to an NTP time server.

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

  • CLOCK_THREAD_CPUTIME_ID - time clock of CPU time.
  • CLOCK_PROCESS_CPUTIME_ID - a high-performance timer for each process from the CPU.
  • CLOCK_MONOTONIC - represents a monotonous time from some unspecified starting point.
  • CLOCK_REALTIME - System-wide real-time clock.

NOTE , but 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

+6
source

Tuomas Pelkonen has already introduced the gettimeofday method, which allows you to get time with a resolution of up to microseconds.

In his example, he goes on to double conversion. I personally wrapped the timeval structure in my own class, which stores scores in seconds and microseconds as integers and handles the add and minus operations correctly.

I prefer to store integers (with exact mathematicians), rather than getting floating point numbers and all their troubles when I can.

0
source

Source: https://habr.com/ru/post/1305367/