Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current time, in milliseconds, in C?

Tags:

c

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

like image 340
user113454 Avatar asked Apr 11 '12 00:04

user113454


People also ask

What is timestamp in C?

time() function in CThis function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.

How do I get milliseconds in Linux?

date +"%T. %6N" returns the current time with nanoseconds rounded to the first 6 digits, which is microseconds. date +"%T. %3N" returns the current time with nanoseconds rounded to the first 3 digits, which is milliseconds.


2 Answers

Check time.h, perhaps something like the gettimeofday() function.

You can do something like

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

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

like image 188
adelbertc Avatar answered Oct 09 '22 15:10

adelbertc


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 fall back to gettimeofday(). The latter has the drawback of being affected by clock adjustments.

On Windows, you can use QueryPerformanceCounter().

This code of mine abstracts all of the above into a simple interface that returns the number of milliseconds as an int64_t. Note that the millisecond values returned are intended only for relative use (e.g. timeouts), and are not relative to any particular time.

like image 39
Ambroz Bizjak Avatar answered Oct 09 '22 15:10

Ambroz Bizjak