Task

Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.

Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.

This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.




#include <stdio.h>
#include <time.h>
 
int identity(int x) { return x; }
 
int sum(int s)
{
  int i;
  for(i=0; i < 1000000; i++) s += i;
  return s;
}
 
#ifdef CLOCK_PROCESS_CPUTIME_ID
/* cpu time in the current process */
#define CLOCKTYPE  CLOCK_PROCESS_CPUTIME_ID
#else
/* this one should be appropriate to avoid errors on multiprocessors systems */
#define CLOCKTYPE  CLOCK_MONOTONIC
#endif
 
double time_it(int (*action)(int), int arg)
{
  struct timespec tsi, tsf;
 
  clock_gettime(CLOCKTYPE, &tsi);
  action(arg);
  clock_gettime(CLOCKTYPE, &tsf);
 
  double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec);
  long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
  return elaps_s + ((double)elaps_ns) / 1.0e9;
}
 
int main()
{
  printf("identity (4) takes %lf s\n", time_it(identity, 4));
  printf("sum      (4) takes %lf s\n", time_it(sum, 4));
  return 0;
}