Sign in to follow this  

Timing a C program

This topic is 4404 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites

This topic is 4404 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this