tags:

views:

171

answers:

4

i need a real time clock in ansi c which provide an accuracy upto miliseconds?

i am working on windows a windows base lib is also acceptable thanx in advance.

+1  A: 

See duplicate answer you need here.

Michael Dorgan
Though it looks like a duplicate, it's really not. There's no answer within the realm of standard C, and none of those answers addressed Windows (the platform specified in this question).
Jerry Coffin
Fair enough - I didn't think through the windows part.
Michael Dorgan
A: 

You cannot be sure in ANSI C that the underlying system provides accuracy in milliseconds. However to achieve maximum detail you can use the clock() function which returns the time since process startup in ticks where the duration of a tick is defined by CLOCKS_PER_SEC:

#include <time.h>

double elapsed; // in milliseconds
clock_t start, end;

start = clock();

/* do some work */

end = clock();
elapsed = ((double) (end - start) * 1000) / CLOCKS_PER_SEC;

From GNU's documentation.

Tomas
`clock()` returns processor time, not wall clock time.
caf
I am aware of that. It is implied in my answer with "since process startup". The question does not make clear whether wall clock time is a requirement.
Tomas
A: 

The ANSI C clock() will give you precision of milliseconds, but not the accuracy, since that is dependent on window's system clock, which has accuracy to 50msec or somewhere around that range. If you need something a little better, then you can use Windows API QueryPerformanceCounter, which has its own caveats as well.

Chris O
A: 

You can't do it with portable code.

Since you're using Windows, you need to start out aware that Windows isn't a real-time system, so nothing you do is really guaranteed to be accurate. That said, you can start with timeBeginPeriod(1); to set the multimedia timer resolution to 1 millisecond. You can then call timeGetTime() to retrieve the current time with 1 ms resolution. When you're done doing timing, you call timeEndPeriod(1) to set the timer resolution back to the default.

Jerry Coffin