1

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
vxcvxcv
  • 15
  • 1
  • 3
  • possible duplicate of [How to measure time in milliseconds using ANSI C?](http://stackoverflow.com/questions/361363/how-to-measure-time-in-milliseconds-using-ansi-c) – WhirlWind May 26 '10 at 15:52
  • Didn't know how to get hyperlink to work in comments or I would have placed my 'answer' here. – Michael Dorgan May 26 '10 at 15:56
  • @Michael I voted to close; it does it automatically. – WhirlWind May 26 '10 at 15:57
  • [Some markdown](http://meta.stackexchange.com/questions/6407/allow-html-tags-in-comments/28523#28523 "but not much") tags are allowed in comments. – progrmr May 26 '10 at 17:55

3 Answers3

2

You can't do it with portable code prior to C11.

Starting with C11, you can use timespec_get, which will often (but doesn't necessarily) provide a resolution of milliseconds or better. Starting from C23, you can call timespec_getres to find out the resolution provided.

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
  • 476,176
  • 80
  • 629
  • 1,111
1

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
  • 5,067
  • 1
  • 35
  • 39
  • `clock()` returns processor time, not wall clock time. – caf May 27 '10 at 00:01
  • 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 May 27 '10 at 08:52
0

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
  • 5,017
  • 3
  • 35
  • 42