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
  // for loop
  // C++ elapsed time calculation
  // print elapsed time in milliseconds
  printf("Time to do 10000 empty loops is %f milliseconds\n",elapsed_time_milli);
  // print elapsed time in seconds
  printf("Time to execute 10000 empty loops is %f seconds",elapsed_time_sec);

Output :


About the Author


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. Required fields are marked *