在Windows上获取毫秒时间

huangapple go评论72阅读模式
英文:

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(&amp;ft);

ts = 0;
ts |= ft.dwHighDateTime;
ts &lt;&lt;= 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(&amp;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 &lt;stdio.h&gt;
#include &lt;time.h&gt;

int main(void)
{
    struct timespec ts;
    timespec_get(&amp;ts, TIME_UTC);
    printf(&quot;Time since epoch: %ld seconds, %ld nanoseconds&quot;, ts.tv_sec, ts.tv_nsec);
}

huangapple
  • 本文由 发表于 2023年2月8日 22:57:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定