ChaoticSomeone
ChaoticSomeone

Reputation: 3

Get time in milliseconds on Windows

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

Upvotes: 0

Views: 459

Answers (2)

dbush
dbush

Reputation: 224387

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;

Upvotes: 2

mediocrevegetable1
mediocrevegetable1

Reputation: 4217

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);
}

Upvotes: 1

Related Questions