How to use clock() function in C++

C++Server Side ProgrammingProgramming

Here we will see how to use the clock() in C++. This clock() is present in the time.h or ctime header file. Here we will find the elapsed time of a process using this clock() function

To get the elapsed time, we can get the time using clock() at the beginning, and at the end of the taks, then subtract the values to get the differences. After that we will divide the difference by CLOCK_PER_SEC (Number of clock ticks per second) to get the processor time.


#include <iostream>
#include <ctime>
using namespace std;
void take_enter() {
   cout << "Press enter to stop the counter" <<endl;
   while(1) {
      if (getchar())
main() {
   // Calculate the time taken by take_enter()
   clock_t t;
   t = clock();
   cout << "Timer starts\n";
   cout << "Timer ends \n";
   t = clock() - t;
   double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
   cout << "The program took "<< time_taken <<" seconds to execute";


Timer starts
Press enter to stop the counter
Timer ends
The program took 3.546 seconds to execute
Updated on 30-Jul-2019 22:30:26