gpt4 book ai didi

c++ - 为什么 CLOCKS_PER_SEC 不是每秒的实际时钟数?

转载 作者:IT老高 更新时间:2023-10-28 12:59:11 45 4
gpt4 key购买 nike

我刚刚编写了这个简短的 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 不匹配?他们甚至不大致相等。这是怎么回事?

最佳答案

clock 返回在您的程序中花费的时间量。每秒总共有 1,000,000 个时钟滴答*。看来您的程序消耗了其中的 60%。

其他 40% 被其他人使用。

*好的,实际上每秒有 1,000,000 个时钟滴答。实际数字已标准化,因此您的程序可以感知 1,000,000 个滴答声。

关于c++ - 为什么 CLOCKS_PER_SEC 不是每秒的实际时钟数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10455905/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com