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 <ctime>
#include <iostream>
using namespace std;
 
int identity(int x) { return x; }
int sum(int num) {
  for (int i = 0; i < 1000000; i++)
    num += i;
  return num;
}
 
double time_it(int (*action)(int), int arg) {
  clock_t start_time = clock();
  action(arg);
  clock_t finis_time = clock();
  return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}
 
int main() {
  cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
  cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
  return 0;
}