您可以为此目的使用 chrono,我很确定它适用于 linux 和 windows。
我不知道有什么方法可以 100% 准确地测量时间。这些计时码表本身会调用一些时间,但它们相对准确。
#include <iostream>
#include <chrono>
bool wait(long long nanoseconds)
{
// if the number of ns to wait is not zero
if(0 != nanoseconds)
{
// init high resolution clock
std::chrono::high_resolution_clock hrc = {};
// get the start and stop timepoints
std::chrono::time_point<std::chrono::high_resolution_clock> start = hrc.now(),
stop = hrc.now();
// calculate the number of ns passed by subtracting the time at the start from the time at the stop
std::chrono::nanoseconds time_passed = stop - start;
// while the number of ns to wait for is bigger than the number of ns passed
while(nanoseconds > time_passed.count())
{
// get the new stop timepoint
stop = hrc.now();
// calculate the new number of ns passed
time_passed = stop - start;
}
// the wait has ended
return true;
}
// the function failed
return false;
}
int main()
{
printf("start\n");
// wait for 5 seconds
wait(5000000000);
printf("stop\n");
getchar();
return 0;
}
您也可以使用 rdtsc 指令以获得更高的准确性,但我无法使示例代码正常工作,所以我还是将其发布。
这是汇编代码(我的 IDE,Visual Studio,不支持 x64 上的内联汇编,所以我不得不单独编写)
.model flat, c
.code
get_curr_cycle proc
cpuid
cpuid
cpuid
rdtsc
shl edx, 32
or edx, eax
mov eax, edx
retn
get_curr_cycle endp
end
这是 c++ 代码。
#include <iostream>
extern "C" unsigned int get_curr_cycle();
bool wait(long long nanoseconds)
{
if(0 != nanoseconds)
{
unsigned int start = get_curr_cycle(),
stop = get_curr_cycle();
unsigned int time_passed = (stop - start);
while(nanoseconds > time_passed)
{
stop = get_curr_cycle();
time_passed = (stop - start);
}
}
return false;
}
int main()
{
printf("start\n");
// wait for 5 seconds
wait(5000000000);
printf("stop\n");
getchar();
return 0;
}