Why is CLOCKS_PER_SEC not the actual number of clocks per second?

后端 未结 6 1590
情话喂你
情话喂你 2020-11-30 03:53

I have just written this short C++ program to approximate the actual number of clock ticks per second.

#include 
#include 

usi         


        
6条回答
  •  情书的邮戳
    2020-11-30 04:47

    Well duh. You don't know how far into the current second you start the timing, do you? So you can get any result from 1 to CLOCKS_PER_SEC. Try this in your inner loop:

    int first_time = time(NULL);
    // Wait for timer to roll over before starting clock!
    while(time(NULL) <= first_time) {}
    
    int first_clock = clock();
    first_time = time(NULL);
    while(time(NULL) <= first_time) {}
    
    int second_time = time(NULL);
    int second_clock = clock();
    
    cout << "Actual clocks per second = " << (second_clock - first_clock)/(second_time - first_time) << "\n";
    
    cout << "CLOCKS_PER_SEC = " << CLOCKS_PER_SEC << "\n";
    

    See ideone for full source code. It reports actual clocks per second as 1000000, as you would expect. (I had to reduce the number of iterations to 2, so that ideone didn't time out.)

提交回复
热议问题