英文:
Get time in milliseconds on Windows
问题
我需要一种获取高精度时间(毫秒或微秒)的方法,用于我正在C(C11)中编写的PRNG算法,因为time(0)
不够精确。
我尝试了几种其他可能的解决方案,这些解决方案我在StackOverflow上找到,但都不适用于我。
无论如何,我的问题现在已经得到解决,感谢@dbush提供的代码。
英文:
I need a way to get the time in a high precision (milliseconds or microseconds) for a PRNG algorithm I'm writing in C (C11), as time(0)
is not precise enough.
I tried using several other possible solutions, which I found on StackOverflow, but none of them worked for me.
Anyways my problem is now fixed, with the help of the code @dbush provided
答案1
得分: 2
你可以使用GetSystemTimeAsFileTime
函数,它会返回自1601年1月1日UTC以来的当前时间,单位为100纳秒。
FILETIME ft;
uint64_t ts;
GetSystemTimeAsFileTime(&ft);
ts = 0;
ts |= ft.dwHighDateTime;
ts <<= 32;
ts |= ft.dwLowDateTime;
请注意,系统时钟的精度可能不是那么高,所以不要期望精确到100纳秒。
另一个选项是QueryPerformanceCounter
函数,它会返回从一个不确定的起始点开始的微秒间隔时间:
LARGE_INTEGER ticks;
QueryPerformanceCounter(&ticks);
uint64_t ts = ticks.QuadPart;
英文:
You can use the GetSystemTimeAsFileTime
function, which gives you the current time in 100ns intervals since 1/1/1601 UTC.
FILETIME ft;
uint64_t ts;
GetSystemTimeAsFileTime(&ft);
ts = 0;
ts |= ft.dwHighDateTime;
ts <<= 32;
ts |= ft.dwLowDateTime;
Note that the system clock is most likely not that precise, so don't expect 100ns granularity.
Another option is QueryPerformanceCounter
, which will give you microsecond intervals from an undetermined starting point:
LARGE_INTEGER ticks;
QueryPerformanceCounter(&ticks);
uint64_t ts = ticks.QuadPart;
答案2
得分: 1
Starting from C11, you can use struct timespec
and timespec_get
to get the same value as time(NULL)
in seconds and nanoseconds:
#include <stdio.h>
#include <time.h>
int main(void)
{
struct timespec ts;
timespec_get(&ts, TIME_UTC);
printf("Time since epoch: %ld seconds, %ld nanoseconds", ts.tv_sec, ts.tv_nsec);
}
英文:
Starting from C11, you can use struct timespec
and timespec_get
to get the same value as time(NULL)
in seconds and nanoseconds:
#include <stdio.h>
#include <time.h>
int main(void)
{
struct timespec ts;
timespec_get(&ts, TIME_UTC);
printf("Time since epoch: %ld seconds, %ld nanoseconds", ts.tv_sec, ts.tv_nsec);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论