我刚刚编写了这个简短的 C++ 程序来估计每秒的实际时钟滴答数。
#include <iostream>
#include <time.h>
using namespace std;
int main () {
for(int i = 0; i < 10 ; i++) {
int first_clock = clock();
int 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";
}
return 0;
}
当我运行程序时,我得到如下所示的输出。
Actual clocks per second = 199139
CLOCKS_PER_SEC = 1000000
Actual clocks per second = 638164
CLOCKS_PER_SEC = 1000000
Actual clocks per second = 610735
CLOCKS_PER_SEC = 1000000
Actual clocks per second = 614835
CLOCKS_PER_SEC = 1000000
Actual clocks per second = 642327
CLOCKS_PER_SEC = 1000000
Actual clocks per second = 562068
CLOCKS_PER_SEC = 1000000
Actual clocks per second = 605767
CLOCKS_PER_SEC = 1000000
Actual clocks per second = 619543
CLOCKS_PER_SEC = 1000000
Actual clocks per second = 650243
CLOCKS_PER_SEC = 1000000
Actual clocks per second = 639128
CLOCKS_PER_SEC = 1000000
为什么每秒的实际时钟滴答数与 CLOCKS_PER_SEC 不匹配?他们甚至不大致相等。这里发生了什么?