首页 > 解决方案 > 在 Windows 10 中将 CLOCKS_PER_SEC 重新定义为更高的数字

问题描述

Windows 10 中的 GNU C++ 编译器返回CLOCKS_PER_SEC = 1000,但我需要测量低于毫秒间隔的算法的编译时间(这是一个学校项目)。有没有办法重新定义CLOCKS_PER_SEC,比如说,一百万(比如基于 UNIX 的操作系统)?另一方面,#define CLOCKS_PER_SEC ((clock_t)(1000000))似乎也不起作用。

标签: c++windows-10ctime

解决方案


简短的回答:没有

长答案:不,但您可以使用QueryPerformanceCounter 函数,这是 MSDN 的一个示例:

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;

这样,您甚至可以测量纳秒,但要注意:在该精度级别上,即使滴答计数也会漂移和抖动,因此您可能永远不会收到完全准确的结果。如果您想要完美的精度,我想您将被迫在适当的专用硬件上使用RTOS ,该硬件可以屏蔽软错误,例如


推荐阅读