LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   quickest way to fetch time in C++ (https://www.linuxquestions.org/questions/programming-9/quickest-way-to-fetch-time-in-c-632318/)

newbix 04-01-2008 09:42 PM

quickest way to fetch time in C++
 
I am trying to optimize a C++ program by counting up the elapsed time in various sections of the program. I need a function that returns time at the millisecond level or better. The program consists of a series of nested loops and I want to track the time taken up by various sections in the innermost loop (so that the sections of code I'm timing execute quickly, but the overall time adds up because of the looping).

I've been using the gettimeofday function to do this (since it gives microseconds), but it turns out to be very slow. When I measure the time elapsed using this function, it looks like most of the time is spent just fetching the current time, which doesn't help me figure out what portions of my code need optimizing. My timer function looks like this:

time_t millitime()
{
struct timeval tm;

gettimeofday(&tm,NULL);

return 1000*tm->tv_sec + tm->tv_usec/1000;
}

Does anyone know of a faster way to retrieve the current time in milliseconds?

Many thanks in advance.

Dan04 04-01-2008 10:06 PM

Have you tried the clock() function?

Hko 04-02-2008 02:12 AM

Quote:

Originally Posted by newbix (Post 3107807)
I am trying to optimize a C++ program by counting up the elapsed time in various sections of the program. I need a function that returns time at the millisecond level or better. The program consists of a series of nested loops and I want to track the time taken up by various sections in the innermost loop (so that the sections of code I'm timing execute quickly, but the overall time adds up because of the looping).

There is a better solution for this problem: use a profiler

newbix 04-02-2008 07:51 AM

Thanks Dan04:

I will try the clock() function today.

Thanks Hko:

I was trying to avoid using a profiler since, for reasons of speed, the code avoids function calls as much as possible.

Also, I would like the flexibility of quickly checking individual statements or groups of statements for speed, or even the overhead involved with the loops themselves, without having to turn those lines into function calls for the profiler to analyze. I didn't think gprof would be convenient to use for that type of line-by-line checking.

However it may be that I am being too paranoid about how long each function call would take, and if I can't come up with a quicker timing function, it seems like gprof will be the better solution.

Thank you...


All times are GMT -5. The time now is 09:43 AM.