Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure the ACTUAL execution time of a C program under Linux?

Tags:

I know this question may have been commonly asked before, but it seems most of those questions are regarding the elapsed time (based on wall clock) of a piece of code. The elapsed time of a piece of code is unlikely equal to the actual execution time, as other processes may be executing during the elapsed 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:

  1. How do I know the precision of getrusage()?
  2. Are there other approaches that can provide higher precision than getrusage()?
like image 452
Dillon Geo Avatar asked Aug 27 '11 16:08

Dillon Geo


People also ask

How do you find the time taken to execute a program in C?

To calculate time taken by a process, we can use clock() function which is available time.

How do you measure execution?

1) Create a loop around whatneeds to be measured, that executes 10, 100, or 1000 times or more. Measure execution time to the nearest 10 msec. Then divide that time bythe number of times the loop executed. If the loop executed 1000 timesusing a 10 msec clock, you obtain a resolution of 10 µsec for theloop.


1 Answers

You can check the real CPU time of a process on linux by utilizing the CPU Time 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; 

Source: http://www.gnu.org/s/hello/manual/libc/CPU-Time.html#CPU-Time

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.

like image 75
Lars Avatar answered Sep 20 '22 17:09

Lars