measuring time

Nov 8, 2011 at 2:21pm
Hello, I want to measure the time my function use to execute. I was trying to use time() and clock() from time.h but it only return it in seconds. How can I measure it in miliseconds?
Nov 8, 2011 at 2:33pm
What you can do is:

(1) clock_t start = clock ();


(2) clock_t timeElapsed = ( clock() - start ) / CLOCKS_PER_SEC;

//this will return in SECONDS the amount of time that have passed from executing (1) until (2)

//if you want it in milliseconds, just multiply timeElapsed by 1000.

Hoe this helps you!
Nov 8, 2011 at 2:58pm
You could use GetTickCount or timeGetTime. These functions don't account for context switches though. If you want to get only the time spent executing your code you should use GetThreadTimes. Call it once before your function and again after your function. Subtract the old kernel time from the new kernel time and the old user time from the new user time then add the differences to get the total time.
Last edited on Nov 8, 2011 at 2:59pm
Nov 9, 2011 at 2:58am
//if you want it in milliseconds, just multiply timeElapsed by 1000.

This will lose precision and give you milliseconds rounded to whole seconds, so 1000, 2000, 3000 and nothing in-between.

The code is also mixing units which will be confusing - at (1) you have ticks stored in a clock_t, at (2) you have seconds in a clock_t. Consistency is important.

At a minimum, you'd want the following:
1
2
clock_t timeElapsed = clock() - start;
unsigned msElapsed = timeElapsed / (CLOCKS_PER_SEC / 1000);

But you'd be better off defining a CLOCKS_PER_MS constant and using:
1
2
3
#define CLOCKS_PER_MS (CLOCKS_PER_SEC / 1000)
clock_t timeElapsed = clock() - start;
unsigned msElapsed = timeElapsed / CLOCKS_PER_MS;
Topic archived. No new replies allowed.