3

Possible Duplicate:
C++ Timer function to provide time in nano seconds

I need to get out of a loop when approaching 3 seconds, so I need to calculate the elapsed time.

I'm moving some code from Java to C, and I was using the easy System.nanoTime() in Java,

How would I do that in C?

I noticed that time(NULL) will return the seconds, but I'm looking for more precision.

Thank you in advance

Community
  • 1
  • 1
David Robles
  • 9,477
  • 8
  • 37
  • 47

2 Answers2

1

For the resolution you want, clock() from the C standard library is sufficient:

#include <time.h>
#define RUNTIME_MAX_SEC 3

clock_t start = clock();
while(clock() - start < CLOCKS_PER_SEC * RUNTIME_MAX_SEC)
{ ... }
Christoph
  • 164,997
  • 36
  • 182
  • 240
0

use gettimeofday , it has microseconds resolution. System.nanoTime() in Java is commonly implemented using gettimeofday on *nixes

nos
  • 223,662
  • 58
  • 417
  • 506
  • Caution; gettimeofday may reports a value in microseconds, but the actual resolution is platform dependent. It is not updated at that rate. – Clifford Feb 19 '10 at 11:55