0

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;
}
4

5 回答 5

5

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;
}
于 2011-08-07T18:55:46.903 回答
3

Execute each calculation thousands of times, in a loop, so that you can overcome the low resolution of time and obtain meaningful results. Remember to divide by the number of iterations when reporting results.

This is not particularly accurate but that probably does not matter for this assignment.

于 2011-08-07T18:45:32.333 回答
2

At least on Unix-like systems, time() only gives you 1-second granularity, so it's not useful for timing things that take a very short amount of time (unless you execute them many times in a loop). Take a look at the gettimeofday() function, which gives you the current time with microsecond resolution. Or consider using clock(), which measure CPU time rather than wall-clock time.

于 2011-08-07T20:16:11.317 回答
1

Your code is executed too fast to be detected by time function returning the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC.

Try to use this piece of code:

inline long getCurrentTime() {
    timeb timebstr;
    ftime( &timebstr );
    return (long)(timebstr.time)*1000 + timebstr.millitm;
}

To use it you have to include sys/timeb.h.

Actually the better practice is to repeat your calculations in the loop to get more precise results.

于 2011-08-07T18:44:27.540 回答
1

You will probably have to find a more precise platform-specific timer such as the Windows High Performance Timer. You may also (very likely) find that your compiler optimizes or removes almost all of your code.

于 2011-08-07T18:53:03.863 回答