Get current time in milliseconds in C?

What is the Java System.currentTimeMillis() equivalence in C?

+6
source share
4 answers

On Linux and other Unix-like systems, you should use clock_gettime (CLOCK_MONOTONIC) . If this is not available (e.g. Linux 2.4), you can return to gettimeofday () . The latter has the disadvantage that the clock settings affect it.

On Windows, you can use QueryPerformanceCounter () .

This code of mine annotates all of the above in a simple interface that returns the number of milliseconds as int64_t. Please note that the returned values ​​in milliseconds are for relative use only (e.g. timeouts) and do not apply to any particular time.

+3
source

Check time.h , maybe something like gettimeofday() function.

You can do something like

 struct timeval now; gettimeofday(&now, NULL); 

Then you can extract the time by getting values ​​from now.tv_sec and now.tv_usec .

+2
source

Here's the time () function, but returns seconds, not milliseconds. If you need more precision, you can use platform-specific functions such as Windows GetSystemTimeAsFileTime () or * nix gettimeofday () .

If you really do not care about the date and time, but just want the time interval between two events, for example:

 long time1 = System.currentTimeMillis(); // ... do something that takes a while ... long time2 = System.currentTimeMillis(); long elapsedMS = time2 - time1; 

then the equivalent of C clock () . On Windows, GetTickCount () is more often used for this purpose.

+1
source

See this topic: http://cboard.cprogramming.com/c-programming/51247-current-system-time-milliseconds.html

It says that the time () function is accurate in seconds, and other libraries are needed for deeper precision ...

0
source

Source: https://habr.com/ru/post/912891/


All Articles