C++: Measure code execution time using Clock function [in milliseconds or seconds]

Problem: How to Measure the execution time of code or function speed in C++?
Language: C++ [CPP]
Solution: Use C++ clock() function to calculate elapsed time of code or function call

How to use clock() function to measure elapsed time?

Below example code is to calculate total elapsed time to execute an empty loop for 10000 times.

clock() prints the elapsed time in milliseconds.
To get it in seconds, you can use CLOCKS_PER_SEC macro

#include <iostream>
#include <time.h> // header file for clock() function
#include <stdio.h> // header file for printf()

int main() {
  //declare start time
  clock_t start_time;
  // declare elapsed time, in milliseconds and seconds
  float elapsed_time_milli,elapsed_time_sec;
  int i;

  // C++ start time
  start_time=clock();
  // for loop
  for(i=0;i<10000;i++);
  // C++ elapsed time calculation
  elapsed_time_milli=float(clock()-start_time);
  // print elapsed time in milliseconds
  printf("Time to do 10000 empty loops is %f milliseconds\n",elapsed_time_milli);
  // print elapsed time in seconds
  elapsed_time_sec=elapsed_time_milli/CLOCKS_PER_SEC;
  printf("Time to execute 10000 empty loops is %f seconds",elapsed_time_sec);
}

Output :

cpp-measure-elapsed-time-output

About the Author

SRINI S

A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps

Leave a Reply

Your email address will not be published.