Timing a C program

Started by
5 comments, last by kadaf 18 years, 4 months ago
I need to be able to time how long certain things took in my program. I tried using the time.h time function...but that only returns a long int in seconds. What I need is something that can time it in milliseconds. And it must be C and not C++.
Advertisement
If Windows is your flavour, check out QueryPerformanceCounter or timeGetTime.
Nah, unfortunately it's gotta work in Unix.
gettimeofday
C has the "clock" function in time.h. It "returns the implementation's best approximation to the processor time used by the program..." (7.23.2.1). There's also a macro called CLOCKS_PER_SEC which gives the frequency of the time returned by clock(). It probably depends on the implementation what sort of frequency you can expect.
http://www.cplusplus.com/ref/ctime
The following code should work on both windows and unix, and has a precission of 1 ms:

#include <sys/timeb.h>...double get_ms_time(void) {        #if defined(WIN32) && (defined(_MSC_VER) || defined(__MINGW32__))                struct _timeb tb;                _ftime(&tb);        #else                struct timeb tb;                ftime(&tb);        #endif        return ((double)tb.time) + ((double)tb.millitm) / 1000.0f;              }
-- Rasmus Neckelmann

This topic is closed to new replies.

Advertisement