【发布时间】:2015-10-22 13:27:51
【问题描述】:
我正在尝试让我的代码测量小于 1 毫秒的持续时间,但我做不到。
我已经四处寻找,但没有设法了解如何去做。我添加了我认为相关的各种代码。
template <class Clock>
void
display_precision()
{
typedef std::chrono::duration<double, std::nano> NS;
NS ns = typename Clock::duration(1);
std::cout << ns.count() << " ns\n";
}
int main()
{
display_precision<std::chrono::high_resolution_clock>();
display_precision<std::chrono::system_clock>();
display_precision<std::chrono::steady_clock>();
std::cout << std::chrono::high_resolution_clock::period::num
<< "/" << std::chrono::high_resolution_clock::period::den;
std::chrono::high_resolution_clock::time_point nowTime;
std::chrono::high_resolution_clock::time_point startTime;
startTime = std::chrono::high_resolution_clock::now();
int count = 0;
do
{
nowTime = std::chrono::high_resolution_clock::now();
std::chrono::high_resolution_clock::duration diff = nowTime - startTime;
__int64 difference = std::chrono::duration_cast<std::chrono::microseconds>(diff).count();
printf("\n%i", difference);
count++;
if (std::chrono::duration_cast<std::chrono::seconds>(diff).count() > 2) { break; }
} while (1);
}
我得到的输出是这样的:
100 ns
100 ns
100 ns
1 / 10000000
和:
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
3000300
如您所见,difference 每毫秒更改一次,并且在此期间保持不变,尽管它同时循环了 15 次左右(尽管据报道我的精度为 100ns)。
另外,这似乎不是 printf 的瓶颈,因为我尝试用数据加载向量并且得到了相同的结果。
[Windows 7 专业版,VS 社区 2013]
【问题讨论】:
-
您使用的是什么操作系统?内核版本?编译器版本? C/C++ 库版本?等等……关于chrono,这里有一个很好的链接:stackoverflow.com/questions/8386128/…
-
这看起来像 Visual Studio,不确定是哪个版本。
-
对不起。编辑了我的帖子。 Windows 7 专业版,VS 社区 2013
-
致 Erik 的评论:是的,我已经看过这个线程,并且我用来在我的机器上测试的一些代码来自那里。
标签: precision milliseconds chrono