3

我做得对吗?有时,我的程序会为计时解决方案打印 2000+,它总是为 CLOCKS_PER_SEC 打印 1000..

我实际计算的值是多少?是每秒时钟数吗?

#include <iostream>
#include <chrono>
#include <thread>
#include <ctime>

std::chrono::time_point<std::chrono::high_resolution_clock> SystemTime()
{
    return std::chrono::high_resolution_clock::now();
}

std::uint32_t TimeDuration(std::chrono::time_point<std::chrono::high_resolution_clock> Time)
{
    return std::chrono::duration_cast<std::chrono::nanoseconds>(SystemTime() - Time).count();
}

int main()
{
    auto Begin = std::chrono::high_resolution_clock::now();
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    std::cout<< (TimeDuration(Begin) / 1000.0)<<std::endl;

    std::cout<<CLOCKS_PER_SEC;
    return 0;
}
4

2 回答 2

5

为了在 Linux 上获得正确的每秒滴答声,您需要使用::sysconf(_SC_CLK_TCK)(在 header 中声明unistd.h)的返回值,而不是宏CLOCKS_PER_SEC

后者是 POSIX 标准中定义的常数——它与 CPU 时钟的每秒实际滴答数无关。例如,请参见手册页clock

C89、C99、POSIX.1-2001。POSIX 要求 CLOCKS_PER_SEC 等于 1000000,与实际分辨率无关。

但是,请注意,即使使用正确的 ticks-per-second 常数,您仍然无法获得每秒的实际 CPU 周期数。“时钟滴答”是 CPU 时钟使用的特殊单位。它与实际 CPU 周期的关系没有标准化的定义。

于 2013-01-23T03:58:30.247 回答
0

在 boost 的库中,有一个计时器类,使用 CLOCKS_PER_SEC 来计算计时器可以经过的最长时间。它说在Windows上CLOCKS_PER_SEC是1000,在Mac OS X,Linux上是1000000。所以在后面的操作系统上,精度更高。

于 2016-08-13T12:52:52.380 回答