开发者

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

i need a real time c开发者_运维百科lock 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 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜