Calculating Execution Time with time() Function in C++

c++ctimetime

I was given the following HomeWork assignment,

Write a program to test on your computer how long it takes to do
nlogn, n2, n5, 2n, and n! additions for n=5, 10, 15, 20.

I have written a piece of code but all the time I am getting the time of execution 0. Can anyone help me out with it? Thanks

#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main()
{
 float n=20;
 time_t start, end, diff;
  start = time (NULL);
  cout<<(n*log(n))*(n*n)*(pow(n,5))*(pow(2,n))<<endl;
  end= time(NULL);
 diff = difftime (end,start);
 cout <<diff<<endl;
 return 0;
}

Best Answer

better than time() with second-precision is to use a milliseconds precision. a portable way is e.g.

int main(){
clock_t start, end;
double msecs;

start = clock();
/* any stuff here ... */
end = clock();
msecs = ((double) (end - start)) * 1000 / CLOCKS_PER_SEC;
return 0;
}
Related Question