user113454
user113454

Reputation: 2373

Get the current time, in milliseconds, in C?

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

Upvotes: 9

Views: 31142

Answers (5)

LeeR
LeeR

Reputation: 608

#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.

Upvotes: 6

Ambroz Bizjak
Ambroz Bizjak

Reputation: 8115

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.

Upvotes: 3

dan04
dan04

Reputation: 91227

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.

Upvotes: 0

adelbertc
adelbertc

Reputation: 7320

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.

Upvotes: 3

apnorton
apnorton

Reputation: 2440

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...

Upvotes: 0

Related Questions