在Windows上,clock()以毫秒为单位返回时间,但是在我正在处理的这个Linux机器上,它将它舍入到最接近的1000,因此精度仅为"秒"级别而不是毫秒级别.
我找到了一个使用QTime该类的Qt解决方案,实例化一个对象并调用start()它然后调用elapsed()以获得经过的毫秒数.
我有点幸运,因为我开始使用Qt,但我想要一个不依赖第三方库的解决方案,
有没有标准的方法来做到这一点?
UPDATE
请不要推荐Boost ..
如果Boost和Qt可以做到这一点,那肯定不是魔术,必须有他们正在使用的标准!
我做得对吗?有时,我的程序会为 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)