O'Reilly logo

SAMS Teach Yourself C++ in 10 Minutes SECOND EDITION by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Timing Your Code

You should always time your code to find out which parts of it are slow. This is an excellent application for test harnesses.

The Standard C library provides a time function for you to use. Unfortunately, it only measures time in one-second increments, so you will have to run many tests to get a time you can measure. For instance:

#include <time.h>

time_t Start;
time_t End;

time(&Start);
for (int Index = 0; Index < 100000; Index++)
{
   int Value = Accumulator.Value();
} ;

time(&end);

double TimeRequired = difftime(Start,End);

Keep in mind that some operations cannot be easily or reliably performed in a loop of this sort. For instance:

 #include <time.h> time_t Start; time_t End; time(&Start); for (int Index = 0; Index < 100000; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required