Current microsecond time in C?

13,741

Solution 1

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.

Solution 2

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

Solution 3

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

Share:
13,741
Sachin Chourasiya
Author by

Sachin Chourasiya

I am a self motivated software engineer.

Updated on July 31, 2022

Comments

  • Sachin Chourasiya
    Sachin Chourasiya over 1 year

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

  • Steve Jessop
    Steve Jessop about 13 years
    Strictly speaking I think it provides that precision, not necessarily that accuracy. But AFAIK it's the best you're going to get for wall clock time.
  • 6502
    6502 about 13 years
    @Steve Jessop: Thanx. Corrected.
  • user2584401
    user2584401 over 11 years
    For higher resolution than microseconds on OS X, try this answer: stackoverflow.com/questions/5167269/…