8

How can I print current microseconds time in C on Unix platform?

Sachin
  • 20,805
  • 32
  • 86
  • 99
  • 1
    Possible duplicate of [Get a timestamp in C in microseconds?](http://stackoverflow.com/questions/5833094/get-a-timestamp-in-c-in-microseconds) Now possible with `timespec_get` from C11: http://stackoverflow.com/a/36095514/895245 – Ciro Santilli OurBigBook.com Mar 18 '16 at 22:49

4 Answers4

7

In Linux and BSDs, you can use the gettimeofday() function. This populates a timeval struct which has a field for seconds since the epoch and a field for microseconds. This function is deprecated. The higher resolution clock_gettime() is the favored replacement, however Mac OS X does not implement it. I'm not sure if Windows implements either of these.

Matt K
  • 13,370
  • 2
  • 32
  • 51
  • For higher resolution than microseconds on OS X, try this answer: http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x – Matt K Dec 07 '12 at 15:35
5

There is no portable (multiplatform) way to get that number. On Linux (or other POSIX systems) for example there is the call gettimeofday that provides exactly that precision (accuracy however will depend if that timing is available and implemented on the specific hardware).

6502
  • 112,025
  • 15
  • 165
  • 265
2

The C standard doesn't provide a standard means for that. However the clock() function returns time in CLOCK's. there are CLOCKS_PER_SEC CLOCK's in a second. On my machine and implementation, CLOCKS_PER_SEC is defined as 1000. Both clock and CLOCKS_PER_SEC are defined in <time.h>. Hope this helped

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
0

If you are on linux, I would check out this site: http://rabbit.eng.miami.edu/info/functions/time.html Particularly the 'gettimeofday' function. Which you can pass a structure, and get the time of day in microseconds.

Adam
  • 707
  • 1
  • 7
  • 15