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

- 36,288
- 32
- 162
- 271

- 2,273
- 9
- 28
- 35
-
1See http://stackoverflow.com/questions/5303751/current-microsecond-time-in-c. Good answers there. – netcoder Apr 11 '12 at 00:57
-
1Possible duplicate of [How to measure time in milliseconds using ANSI C?](http://stackoverflow.com/questions/361363/how-to-measure-time-in-milliseconds-using-ansi-c) – Ciro Santilli OurBigBook.com Mar 18 '16 at 22:50
5 Answers
#include <sys/time.h>
/**
* @brief provide same output with the native function in java called
* currentTimeMillis().
*/
int64_t currentTimeMillis() {
struct timeval time;
gettimeofday(&time, NULL);
int64_t s1 = (int64_t)(time.tv_sec) * 1000;
int64_t s2 = (time.tv_usec / 1000);
return s1 + s2;
}
I write this function just like System.currentTimeMillis()
in Java, and they have the same output.

- 568
- 6
- 10
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
.

- 7,270
- 11
- 47
- 70
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.

- 7,809
- 1
- 38
- 49
-
`CLOCK_MONOTONIC` is not quite equivalent to the java function, as the java function is also affected by wallclock adjustments. It's the right choice for interval timers, of course, but if the OP wants a wallclock time it's not going to help. – bdonlan May 05 '12 at 06:25
See this thread: http://cboard.cprogramming.com/c-programming/51247-current-system-time-milliseconds.html
It says that the time() function is accurate to seconds, and deeper accuracy requires other libraries...

- 2,430
- 1
- 19
- 34
There's the time() function, but it returns seconds, not milliseconds. If you need greater precision, you can use platform-specific functions like Windows' GetSystemTimeAsFileTime() or *nix's gettimeofday().
If you don't actually care about the date and time but just want to time the interval between two events, like this:
long time1 = System.currentTimeMillis();
// ... do something that takes a while ...
long time2 = System.currentTimeMillis();
long elapsedMS = time2 - time1;
then the C equivalent is clock(). On Windows, it's more common to use GetTickCount() for this purpose.

- 87,747
- 23
- 163
- 198