我做得对吗?有时,我的程序会为 chrono 解决方案打印 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;
}
Run Code Online (Sandbox Code Playgroud)
为了在 Linux 上获得正确的每秒滴答数,您需要使用::sysconf(_SC_CLK_TCK)(在 header 中声明unistd.h)的返回值,而不是宏CLOCKS_PER_SEC。
后者是 POSIX 标准中定义的常量——它与 CPU 时钟的每秒实际滴答数无关。例如,请参见手册页clock:
C89、C99、POSIX.1-2001。POSIX 要求 CLOCKS_PER_SEC 等于 1000000,与实际分辨率无关。
但是,请注意,即使使用正确的每秒滴答数常量,您仍然无法获得每秒实际 CPU 周期数。“时钟滴答”是CPU时钟使用的特殊单位。没有关于它与实际 CPU 周期的关系的标准化定义。