Measure time to execute a piece of code

S

saurabh.ss

Hi
I want to measure the time required to execute a piece of code.
For example, I want to know the time required to execute a given
function. How do I do it within C++? I know I got to use a library
called ctime. But I dont know what functions to use. Please tell me.
 
M

MadhavC

I want to measure the time required to execute a piece of code.
For example, I want to know the time required to execute a given
function. How do I do it within C++? I know I got to use a library
called ctime. But I dont know what functions to use. Please tell me.

include time.h in your C++ file

clock_t start, finish;
start = clock();

// your code here

finish = clock();

( (finish - start)/CLOCKS_PER_SEC )
should give the time taken by your code

~Madhav
 
S

saurabh.ss

MadhavC said:
include time.h in your C++ file

clock_t start, finish;
start = clock();

// your code here

finish = clock();

( (finish - start)/CLOCKS_PER_SEC )
should give the time taken by your code

~Madhav

But this gives time in seconds, right? My execution time may be in
milliseconds (or even less). The code you gives 0 time for all
executions. Is there a method to obtain greater resolution?
 
M

MadhavC

But this gives time in seconds, right? My execution time may be in
milliseconds (or even less). The code you gives 0 time for all
executions. Is there a method to obtain greater resolution?

simply don't devide by CLOCKS_PER_SEC
(finish - start) will give you the CPU clocks occured in between.
And I am not sure if sombody can get time detailed to less than the CPU
clock

~Madhav
 
G

Gerard Kramer

If you are on a unix flavour, perhaps a util named gprof is useful. It
gives you detailed information, including time spent at a particular
function, number of calls, etc.

I suppose (?) other systems have something similar.
 
J

Jerry Coffin

@y41g2000cwy.googlegroups.com>, (e-mail address removed)
says...

[ ... ]
( (finish - start)/CLOCKS_PER_SEC )

Try using:

(double(finish - start)/CLOCKS_PER_SEC)

and you may find the results somewhat more useful.
 
B

bitkidoku

It works as the way you explained but it is compact and has a couple of
more features. I didnt used it in a year but I remember it's resolution
is below 1 sec. And I looked at the code and I dont see a reason for
resolution to be 1 sec. Am I missing something too? (Maybe one of us
should try to execute the sample ;) )
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top