有没有办法使用跨平台方法在 C 中获得毫秒精度、准确(至少在几毫秒内)时间?
在 POSIX 系统上,我可以使用 sys/time.h,但这不是跨平台的。
stdlib time() 函数仅提供二级精度
有没有办法使用跨平台方法在 C 中获得毫秒精度、准确(至少在几毫秒内)时间?
在 POSIX 系统上,我可以使用 sys/time.h,但这不是跨平台的。
stdlib time() 函数仅提供二级精度
我还没有找到一个跨平台的解决方案来测量 C 中的时间,本身。但是,我所做的是对 Unix 和 Windows 使用几乎相同的功能。我创建了这个要点,因为我每次都必须重新查找它。简而言之:
#include <time.h>
long diff_micro(struct timespec *start, struct timespec *end)
{
/* us */
return ((end->tv_sec * (1000000)) + (end->tv_nsec / 1000)) -
((start->tv_sec * 1000000) + (start->tv_nsec / 1000));
}
long diff_milli(struct timespec *start, struct timespec *end)
{
/* ms */
return ((end->tv_sec * 1000) + (end->tv_nsec / 1000000)) -
((start->tv_sec * 1000) + (start->tv_nsec / 1000000));
}
int main(int argc, char **argv)
{
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
// Activity to be timed
sleep(1000);
clock_gettime(CLOCK_MONOTONIC, &end);
printf("%ld us\n", diff_micro(&start, &end));
printf("%ld ms\n", diff_milli(&start, &end));
return 0;
}
#include <Windows.h>
long diff_micro(LARGE_INTEGER *start, LARGE_INTEGER *end)
{
LARGE_INTEGER Frequency, elapsed;
QueryPerformanceFrequency(&Frequency);
elapsed.QuadPart = end->QuadPart - start->QuadPart;
elapsed.QuadPart *= 1000000;
elapsed.QuadPart /= Frequency.QuadPart;
return elapsed.QuadPart;
}
long diff_milli(LARGE_INTEGER *start, LARGE_INTEGER *end)
{
LARGE_INTEGER Frequency, elapsed;
QueryPerformanceFrequency(&Frequency);
elapsed.QuadPart = end->QuadPart - start->QuadPart;
elapsed.QuadPart *= 1000;
elapsed.QuadPart /= Frequency.QuadPart;
return elapsed.QuadPart;
}
int main(int argc, char **argv)
{
LARGE_INTEGER StartingTime, EndingTime;
QueryPerformanceCounter(&StartingTime);
// Activity to be timed
Sleep(1000);
QueryPerformanceCounter(&EndingTime);
printf("%ld us\n", diff_micro(&StartingTime, &EndingTime));
printf("%ld ms\n", diff_milli(&StartingTime, &EndingTime));
return 0;
}
最好的方法是使用std::chrono
#include <chrono>
...
auto begin = std::chrono::high_resolution_clock::now();
...
auto end = std::chrono::high_resolution_clock::now();
elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();