gpt4 book ai didi

c++ - 如何测量亚秒级持续时间?

转载 作者:可可西里 更新时间:2023-11-01 09:47:33 25 4
gpt4 key购买 nike

在我的类似计算器的程序中,用户选择要计算的内容和数量(例如,圆周率有多少位,质数有多少等)。我使用 time(0) 检查经过的计算时间以触发超时条件。如果计算在没有超时的情况下完成,我还将打印所用的计算时间,其值存储在 double 中,difftime() 的返回类型。

我刚刚发现计算的时间值仅以秒为单位。我不希望用户输入 100 和 10000 个结果都打印 0e0 秒的计算持续时间。例如,我希望它们分别打印 1.23e-64.56e-3 秒的持续时间(尽可能准确地测量机器 - 我更熟悉Java 提供的准确性以及科学测量的准确性,因此这是个人偏好)。

我看过其他问题的答案,但它们没有帮助,因为 1) 我不会多线程(在我的工作环境中不是首选)。 2) 我不能使用 C++11 或更高版本。

在规定的约束条件下,如何获得比秒更准确的持续时间值作为整数值?

编辑:首选独立于平台和机器的解决方案,否则 Windows 也可以,谢谢!

编辑 2:我的笔记本也没有连接到互联网,所以没有下载像 Boost 这样的外部库(Boost 是什么?)。我必须自己编写任何代码。

最佳答案

您可以使用 QueryPerformanceCounter (QPC)这是 Windows API 的一部分,用于进行高分辨率时间测量。

LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
LARGE_INTEGER Frequency;

QueryPerformanceFrequency(&Frequency);
QueryPerformanceCounter(&StartingTime);

// Activity to be timed

QueryPerformanceCounter(&EndingTime);
ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;


//
// We now have the elapsed number of ticks, along with the
// number of ticks-per-second. We use these values
// to convert to the number of elapsed microseconds.
// To guard against loss-of-precision, we convert
// to microseconds *before* dividing by ticks-per-second.
//

ElapsedMicroseconds.QuadPart *= 1000000;
ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;

关于c++ - 如何测量亚秒级持续时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34583761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com