In this article we will discuss how to measure execution time of any operation in C++.

Many time we encounter a situation, where we need to calculate the execution time of many operations to check performance. For example,

  • How much time was taken to push data in a vector etc.
  • How much time spent in searching data from a datastructure.
  • How much time was taken to send or receive a message through network etc.

To do that we will use boost::posix_time::ptime and boost::posix_time::time_duration types.

boost::posix_time::ptime represents a particular time point
boost::posix_time::time_duration represents a duration / difference between two time points.

Calculating Execution / Elapsed Time

To Measure execution time we will fetch the current time 2 times, one before the operation and one after the operation.
Difference between these two timestamps will give us the execution time of the operation i.e.

Start Time = Get Current Time
Execute Task
End Time = Get Current Time
Time Duration = End Time – Start Time

Suppose our task is to insert 9 Millions strings to a vector of strings. Let’s see how to measure the execution time using
above algo and ptime & time_duration i.e.

Now from boost::posix_time::time_duration we can get hours, minutes & Second field using its member functions i.e.

Total Time Elapsed in milliseconds, microseconds & nanoseconds

We can also get the total time difference in milliseconds, microseconds & Nano seconds i.e.

Getting Total Execution Time in MilliSeconds

Getting Total Execution Time in MicroSeconds

Getting Total Execution Time in NanoSeconds

Complete working example is as follows,


To compile the above code use following command in linux,



Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.