Calculating time of execution with time() function

前端 未结 5 1409
盖世英雄少女心
盖世英雄少女心 2020-12-07 06:12

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

相关标签:
5条回答
  • 2020-12-07 06:45

    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.

    0 讨论(0)
  • 2020-12-07 06:50

    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.

    0 讨论(0)
  • 2020-12-07 06:53

    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;
    }
    
    0 讨论(0)
  • 2020-12-07 07:02

    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.

    0 讨论(0)
  • 2020-12-07 07:10

    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.

    0 讨论(0)
提交回复
热议问题