www.apress.com

19/11/19

Timing Things in C++

by Will Briggs

Note: to understand this example, you should know how to use arithmetic in C++, call functions, and use for-loops and arrays. Templates wouldn’t hurt but you don’t really have to know them.


The basics: measuring in seconds

If you want to measure things in C++, here’s an easy way: use the built-in time function. It’s in #include <ctime>, and it returns the time in seconds since (usually) midnight, January 1, 1970. You gotta start somewhere.


     //Program to time a sloooooow user
     // -- from the APress blog, http://blog.apress.com

     #include <iostream>
     #include <ctime>    //for time function

     using namespace std;

     int main()
     {
          //Time the user’s response
          time_t start = time(nullptr);

          cout << "How long is it going to take you to hit enter, anyway?";
          cin.get(); //get a character -- any character
               //  including '\n', the end of line character

          time_t end   = time(nullptr);

          //Report that time
          cout << "Apparently, it's going to take you "
               << end - start << " seconds.\n";

          return 0;
     }


time_t is a type that comes with ctime; I’ve always just treated it as an int, and it’s always worked.

The nullptr in time(nullptr) is there because time expects an argument I don't want or need for it to use. I give it nullptr as a pacifier, and just use the return value.


Seconds – seriously? Computers are fast!

If you’re timing something the computer does, though, it’s likely to be done in less than a second. Can we get finer resolution?

The ISO committee had mercy on us when they made the C++11 standard (your compiler almost certainly is at least this far along), and gave us extra tools. The tools are in #include <chrono>; they include

high_resolution_clock::time_point
and
duration<double, std::milli>.

That time_point is what you expect: a point in time. duration is a type for durations; we give it std::milli so its count function will return how long it is in milliseconds, and we give it double so we can get fractions of those milliseconds. (If you like you can instead use, say, std::micro for microseconds; see https://en.cppreference.com/w/cpp/chrono/duration for more options.)

One more thing: high_resolution_clock::now(), which returns the time, right now.

The example below uses these things to time a simple function: first, it gets the current time; then it calls the function; then it gets the new current time, and reports the difference.
 

     //Program to time a (relatively) fast function
     // -- from the APress blog, http://blog.apress.com

     #include <iostream>
     #include <chrono>            //for high_resolution_clock, now, duration

     using namespace std;
     using namespace std::chrono; //for those things in <chrono>

     //Returns index of thingToFind, in array numbers
     int linearSearch(int numbers[], int size, int thingToFind);

     int main()
     {
          //Let's have an array to search
          const int ARRAY_SIZE = 10000;
          int myNumbers[ARRAY_SIZE];
          for (int i = 0; i < ARRAY_SIZE; ++i) myNumbers[i] = i;

          //Time linear search
          high_resolution_clock::time_point start = high_resolution_clock::now();     //get the time...

          linearSearch(myNumbers, ARRAY_SIZE, 90210);                                           //search for something...

          high_resolution_clock::time_point end   = high_resolution_clock::now();     //...get the time again

          //How long did that take?
          duration<double, std::milli> timeRequired = (end - start);

          //Let's get milliseconds out of that, and report
          cout << "That function zipped by with only " << timeRequired.count() << " milliseconds.\n";

          return 0;
     }

     int linearSearch(int numbers[], int size, int thingToFind)
     {
          int result   =    -1; //conventional for "not found"
          bool isFound = false; //not found yet...

          for (int i = 0; i < size && ! isFound; ++i)
               if (numbers[i] == thingToFind) //found it!
               {
                    result = i; isFound = true;
               }

          return result;
     }

 

This should enable you to time things in C++ to any resolution you want; make your own stopwatch class; and annoy users with rude remarks about how slow they are. Enjoy!


About the Author

Will Briggs, PhD is a professor of computer science at the University of Lynchburg in Virginia.  He has 20+ years of experience teaching C++, 12 of them using earlier drafts of this book, and about as many years teaching other languages including C, LISP, Pascal, PHP, PROLOG, and Python.  His primary focus is teaching of late while also active in research in artificial intelligence.

This article was contributed by Will Briggs, author of C++ for Lazy Programmers.