Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function Timer

Status
Not open for further replies.

ernesth

Technical User
Jan 17, 2002
15
0
0
US
hello,
I am attempting to time some algorithms that I am testing, but, it seems as though I can't figure out how to time with enough precision (as you can probably guess, I keep getting run times of 0).
The method that I am using is as follows:
#include <time.h>

clock_t start, finish;
float runningTime;

start = clock();

//call function to be timed

finish = clock();

runningTime = (float) (finish-start)/CLOCKS_PER_SEC;

How do I get the time to be more precise? I have tried other forms of the method shown above, but have not had any real success. Most of the timing methods that I have looked up only deal with obtaining various forms of the date, or the time of day, not with being able to time small algorithms. Is there a method where I can call clock(), or some form of clock(), and receive the time in microseconds or nanoseconds?
Any help will be appreciated.

Thanks,
ErnestH

 
Guess this is what you need...

tiemval already exists,it looks like this:

struct timeval{
long tv_sec; /* seconds since 00:00:00 GMT,Jan 1,1970 */
long tv_usec;/* and microseconds */
};

use it like this:

timeval thetime;

gettimeofday(&thetime,null);

simple hug?
Greetz,

The Muppeteer.

themuppeteer@hotmail.com

Don't eat yellow snow...
 
hello,
I found a solution which works on unix, it is the high resolution timer which measures out to the ns.

#include <sys/time.h>

hrtime_t = start, finish;
start = gethrtime();
//function to be timed
finish = gethrtime();

thanks for your help
 
Hi,
you may have to execute you function 10 or 100 or 1000000 times in a for loop and then divide the time it takes by the number of iterations to get enough sample time to get a valid measurement.

Make sure you execute a for loop calling an empty function so you can remove the function call overhead from your calculation.

If the function call overhead is more than the actual code inside the function itself then you should consider making it a macro.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top