• Welcome to Computer Association of SIUE - Forums.
 

Elapsed time in C++

Started by Tangent Orchard, 2010-04-13T16:31:26-05:00 (Tuesday)

Previous topic - Next topic

Tangent Orchard

I need to run and time some C++ algorithms for a Statistics course, and I just wanted to see if anyone knew what the best way of counting time in C++ was.  I have some code that utilizes time_t variables for an old CS438 (Artificial Intelligence) program, but I can't currently recall if that's the best way.  I'm not picky on the units; seconds or milliseconds are fine.

Thanks!

William Grim

#1
Use clock(3) by wrapping it around your actual work units.  Depending on how complex your code is and what exactly you're trying to time (i.e. making sure you ignore I/O), you may need to make several clock measurements, summing the results.
William Grim
IT Associate, Morgan Stanley

Travis W

I have some code for 340 that sounds like it is what you are looking for.
Remind me tomorrow and i will show it to you.

Mark Sands

Here's a really cool way:

http://gist.github.com/366681

To briefly explain, the clock is started in the constructor and stopped in the destructor. So whenever you create a Timer object, it will count the time it's in scope. In this example, the Timer's scope is the entire `main`, but you can easily use this in any function you want. A simple `int foo() { Timer t; }` will also work as expected.
Mark Sands
Computer Science Major

William Grim

While I think the use of that C++ Timer class is a fancy approach, I don't think it's useful for performing sophisticated timings.  I think a more useful approach is my original idea of updating a variable any time real work is done, providing a cumulative amount of time, ignoring things you don't care about (presumably I/O... unless you do care about that).

Note that if you do go with an OO Timer approach, put all your code in a header and make the methods inline.  You aren't trying to time the timer.
William Grim
IT Associate, Morgan Stanley

Adam C

This depends on just how sophisticated you're looking for, and the level of precision you need. If you want the most possible control and precision, Grim's method will be best. Otherwise, I did this for 340 back when I took it and it worked well for me.

double time_this(void (*f)()){
   clock_t start;
   start = clock();
   f();
   return ((double)(clock()-start)/CLOCKS_PER_SEC);
}

//example use:

double time = time_this(&load_dictionary);
cout << "Dictionary loaded in: " << time << " seconds." << endl;

thatguy

#Something witty

Tangent Orchard

Thanks for your input, everyone! =) It worked perfectly, and I finished my project easily.