I know this question may have been commonly asked before, but it seems most of those questions are regarding the transcurrido time (based on wall clock) of a piece of code. The transcurrido time of a piece of code is unlikely equal to the real execution time, as other processes may be executing during the transcurrido time of the code of interest.
I used getrusage() to get the user time and system time of a process, and then calculate the actual execution time by (user time + system time). I am running my program on Ubuntu. Here are my questions:
- How do I know the precision of getrusage()?
- Are there other approaches that can provide higher precision than getrusage()?
preguntado el 27 de agosto de 11 a las 16:08
You can check the real CPU time of a process on linux by utilizing the Tiempo de CPU functionality of the kernel:
#include <time.h> clock_t start, end; double cpu_time_used; start = clock(); ... /* Do the work. */ end = clock(); cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
That way, you count the CPU ticks or the real amount of instructions worked upon by the CPU on the process, thus getting the real amount of work time.
The getrusage() function is the only standard/portable way that I know of to get "consumed CPU time".
There isn't a simple way to determine the precision of returned values. I'd be tempted to call the getrusage() once to get an initial value, and the call it repeatedly until the value/s returned are different from the initial value, and then assume the effective precision is the difference between the initial and final values. This is a hack (it would be possible for precision to be higher than this method determines, and the result should probably be considered a worst case estimate) but it's better than nothing.
I'd also be concerned about the accuracy of the values returned. Under some kernels I'd expect that a counter is incremented for whatever code happens to be running when a timer IRQ occurs; and therefore it's possible for a process to be very lucky (and continually block just before the timer IRQ occurs) or very unlucky (and unblock just before the timer IRQ occurs). In this case "lucky" could mean a CPU hog looks like it uses no CPU time, and "unlucky" could means a process that uses very little CPU time looks like a CPU hog.
For specific versions of specific kernels on specific architecture/s (potentially depending on if/when the kernel is compiled with specific configuration options in some cases), there may be higher precision alternatives that aren't portable and aren't standard...
You can use this piece of code :
#include <sys/time.h> struct timeval start, end; gettimeofday(&start, NULL); . . . gettimeofday(&end, NULL); delta = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; printf("Time is : %f\n",delta);
It will show you the execution time for piece of your code