Get time spent between two iterations in C

I have threads, a stream function contains a loop and iterations over a specific period of time.

As an example:

void *start(void *p) // This function is called at the thread creation
{
      int i = 0;

      while (i < 10){
          i++;
      }
} // NOTE THAT THIS FUNCTION IS AN EXAMPLE, the iteration can be small or high.

How can I track the time spent between two iterations? (Considering the fact that I have many threads working at the same time)

I heard about the function clock()and the following operation to determine the time spent on two outputs clock():

(double)(begin - end) / CLOCKS_PER_SEC;

How can I get such information in an effective way?

+4
source share
1 answer

I suggest using the POSIX function clock_gettime:

#include <time.h>

timespec real_startTime;
timespec real_endTime;      

// Start time measurement
if(clock_gettime(CLOCK_REALTIME, &real_startTime) != 0)
{
    perror("Error on fetching the start-time");
    exit(EXIT_FAILURE);
}

// Do some long running operation that should be measured

// Stop time measurement
if(clock_gettime(CLOCK_REALTIME, &real_endTime) != 0)
{
    perror("Error on fetching the end-time");
    exit(EXIT_FAILURE);
}

double real_runTime = (real_endTime.tv_sec + real_endTime.tv_nsec / 1000.0 / 1000.0 / 1000.0) - (real_startTime.tv_sec + real_startTime.tv_nsec / 1000.0 / 1000.0 / 1000.0);

, , "" , - ( - ..), clock, .

Excerp clock_gettime man:

, CLOCK_REALTIME. .

Excerp clock man:

clock()         .


EDIT: , - ( 0 10), , - , , I/O ..).

+2

All Articles