How to resolve the algorithm Time a function step by step in the C++ programming language

Published on 7 June 2024 03:52 AM

How to resolve the algorithm Time a function step by step in the C++ programming language

Table of Contents

Problem Statement

Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Time a function step by step in the C++ programming language

Code Explanation:

The C++ code demonstrates how to measure the execution time of functions using two different approaches.

First Approach:

func-time.cpp:

  • It uses the time_it function, which takes a function pointer and an argument as parameters.
  • time_it calculates the elapsed time between calling the function and finishing its execution.
  • It outputs the execution time of two sample functions: identity (which simply returns its input) and sum (which iterates and adds a large number of integers).

Second Approach:

func-time-lambda.cpp:

  • It uses C++20 features, specifically lambda functions and the std::chrono library.
  • It defines a generic measure function that takes a function object as a parameter.
  • measure uses std::chrono::steady_clock to measure the time elapsed while executing the function object.

Execution Time Comparison:

The execution time reported by both approaches should be similar. However, the second approach using C++20 features may provide more accurate and portable measurements due to improved timer functionality.

Code Overview:

identity Function:

  • A simple function that returns its input integer.

sum Function:

  • A function that iterates 1,000,000 times and adds each iteration value to the input number.

time_it Function:

  • Uses the clock function to measure the elapsed time between calling the function and the function returning.

measure Function:

  • Using lambda functions, it takes a function object as input and measures its execution time using std::chrono::steady_clock.

main Function:

  • Calls time_it for the identity and sum functions and outputs their execution times.
  • For the second approach, it defines lambda functions for identity and addmillion and then uses measure to measure their execution times.

Compilation:

  • For the first approach, compile using g++ -std=c++20 -Wall -Wextra -pedantic -O0 func-time.cpp -o func-time.
  • For the second approach, no specific compilation flags are needed, as it uses standard C++20 features.

Source code in the cpp programming language

#include <ctime>
#include <iostream>
using namespace std;

int identity(int x) { return x; }
int sum(int num) {
  for (int i = 0; i < 1000000; i++)
    num += i;
  return num;
}

double time_it(int (*action)(int), int arg) {
  clock_t start_time = clock();
  action(arg);
  clock_t finis_time = clock();
  return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}

int main() {
  cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
  cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
  return 0;
}


// Compile with:
// g++ -std=c++20 -Wall -Wextra -pedantic -O0 func-time.cpp -o func-time

#include <iostream>
#include <chrono>

template<typename f>
double measure(f func) {
    auto start = std::chrono::steady_clock::now(); // Starting point
    (*func)(); // Run the function
    auto end = std::chrono::steady_clock::now(); // End point
    
    return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); // By default, return time by milliseconds
}

/*
Test functions:
    identity(): returns a number
    addmillion(): add 1,000,000 to a number, one by one, using a for-loop
*/

int identity(int x) { return x; }

int addmillion(int num) {
    for (int i = 0; i < 1000000; i++)
        num += i;
    return num;
}

int main() {
    double time;
    time = measure([](){ return identity(10); });
    // Shove the function into a lambda function.
    // Yeah, I couldn't think of any better workaround.
    std::cout << "identity(10)\t\t" << time << " milliseconds / " << time / 1000 << " seconds" << std::endl; // Print it
    time = measure([](){ return addmillion(1800); });
    std::cout << "addmillion(1800)\t" << time << " milliseconds / " << time / 1000 << " seconds" << std::endl;
    
    return 0;
}


  

You may also check:How to resolve the algorithm Loops/While step by step in the Java programming language
You may also check:How to resolve the algorithm Sort using a custom comparator step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm String interpolation (included) step by step in the AWK programming language
You may also check:How to resolve the algorithm Singly-linked list/Element insertion step by step in the Ada programming language
You may also check:How to resolve the algorithm QR decomposition step by step in the Common Lisp programming language