我做得对吗?有时,我的程序会为时序解决方案打印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;
}发布于 2013-01-23 11:58:30
为了在Linux上获得每秒的正确滴答次数,您需要使用::sysconf(_SC_CLK_TCK)的返回值(在头文件unistd.h中声明),而不是宏CLOCKS_PER_SEC。
后者是POSIX标准中定义的常量-它与CPU时钟每秒的实际滴答数无关。例如,请参见clock的手册页
C89,C99,POSIX.1-2001。POSIX要求CLOCKS_PER_SEC等于1000000,与实际分辨率无关。
但是,请注意,即使使用了正确的每秒滴答数常量,您仍然无法获得每秒的实际CPU周期数。“时钟滴答”是CPU时钟使用的特殊单位。对于它与实际CPU周期的关系,没有标准化的定义。
发布于 2016-08-13 20:52:52
在boost的库中,有一个timer类,使用CLOCKS_PER_SEC计算计时器可以经过的最大时间。它说在Windows上CLOCKS_PER_SEC是1000,而在Mac和Linux上是1000000。因此,在后一种OSs上,准确率更高。
https://stackoverflow.com/questions/14472073
复制相似问题