Measuring Execution Time of a Function in C++

Execution time of C program

CLOCKS_PER_SEC is a constant which is declared in <time.h>. To get the CPU time used by a task within a C application, use:

clock_t begin = clock();

/* here, do your time-consuming job */

clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

Note that this returns the time as a floating point type. This can be more precise than a second (e.g. you measure 4.52 seconds). Precision depends on the architecture; on modern systems you easily get 10ms or lower, but on older Windows machines (from the Win98 era) it was closer to 60ms.

clock() is standard C; it works "everywhere". There are system-specific functions, such as getrusage() on Unix-like systems.

Java's System.currentTimeMillis() does not measure the same thing. It is a "wall clock": it can help you measure how much time it took for the program to execute, but it does not tell you how much CPU time was used. On a multitasking systems (i.e. all of them), these can be widely different.

Measuring execution time of a function in C++

It is a very easy-to-use method in C++11. You have to use std::chrono::high_resolution_clock from <chrono> header.

Use it like so:

#include <chrono>

/* Only needed for the sake of this example. */
#include <iostream>
#include <thread>

void long_operation()
{
/* Simulating a long, heavy operation. */

using namespace std::chrono_literals;
std::this_thread::sleep_for(150ms);
}

int main()
{
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::milliseconds;

auto t1 = high_resolution_clock::now();
long_operation();
auto t2 = high_resolution_clock::now();

/* Getting number of milliseconds as an integer. */
auto ms_int = duration_cast<milliseconds>(t2 - t1);

/* Getting number of milliseconds as a double. */
duration<double, std::milli> ms_double = t2 - t1;

std::cout << ms_int.count() << "ms\n";
std::cout << ms_double.count() << "ms\n";
return 0;
}

This will measure the duration of the function long_operation.

Possible output:

150ms
150.068ms

Working example: https://godbolt.org/z/oe5cMd

How to get execution time of c program?

Contrary to popular belief, the clock() function retrieves CPU time, not elapsed clock time as the name confusingly may induce people to believe.

Here is the language from the C Standard:

7.27.2.1 The clock function

Synopsis

#include <time.h>
clock_t clock(void);

Description

The clock function determines the processor time used.

Returns

The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC. If the processor time used is not available, the function returns the value (clock_t)(−1). If the value cannot be represented, the function returns an unspecified value.

To retrieve the elapsed time, you should use one of the following:

  • the time() function with a resolution of 1 second
  • the timespec_get() function which may be more precise, but might not be available on all systems
  • the gettimeofday() system call available on linux systems
  • the clock_gettime() function.

See What specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX? for more information on this subject.

Here is a modified version using gettimeoday():

#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>

int main() {
struct timeval start, end;

gettimeofday(&start, NULL);
sleep(3);
gettimeofday(&end, NULL);

double time_taken = end.tv_sec + end.tv_usec / 1e6 -
start.tv_sec - start.tv_usec / 1e6; // in seconds

printf("time program took %f seconds to execute\n", time_taken);
return 0;
}

Output:


time program took 3.005133 seconds to execute

Measure execution time in C (on Windows)

You can use QueryPerformanceCounter and QueryPerformanceFrequency :

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main(void)
{
LARGE_INTEGER frequency;
LARGE_INTEGER start;
LARGE_INTEGER end;
double interval;

QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);

// code to be measured

QueryPerformanceCounter(&end);
interval = (double) (end.QuadPart - start.QuadPart) / frequency.QuadPart;

printf("%f\n", interval);

return 0;
}

Getting 0 when trying to measure the execution time of function in C

The time difference is too small to be measured by this method, without adding more code to execute. – Weather Vane

Usually, you contrive a way to measure a large number of loops of what you want to time. 10, 100, 1000, whatever produces a significant result. Bear in mind too that on a multi-tasking OS each iteration will take a slightly different time, and so you'll also establish a typical average.The result might also be affected by processor caching and/or file caching. – Weather Vane

Measure the execution time of a function call in C++

On Windows, you can get accurate measurements with QueryPerformanceCounter.



Related Topics



Leave a reply



Submit