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