Home > Enterprise >  Total time in different parts of recursive function
Total time in different parts of recursive function

Time:07-15

I am new to C and I need to measure the total time for different parts of a recursive function. A simple example to show where I get so far is:

#include <iostream>
#include <unistd.h>
#include <chrono>
using namespace std;
using namespace std::chrono;

int recursive(int);
void foo();
void bar();

int main() {
    int n = 5;  // this value is known only at runtime
    int result = recursive(n);
    return 0;
}

int recursive(int n) {
    auto start = high_resolution_clock::now();
    if (n > 1) { recursive(n - 1); n = n - 1; }
    auto stop = high_resolution_clock::now();
    auto duration_recursive = duration_cast<microseconds>(stop - start); 

    cout << "time in recursive: " << duration_recursive.count() << endl;
    //
    // .. calls to other functions and computations parts I don't want to time
    //
    start = high_resolution_clock::now();
    foo();
    stop = high_resolution_clock::now();
    auto duration_foo = duration_cast<seconds>(stop - start);
    cout << "time in foo: " << duration_foo.count() << endl;
    //
    // .. calls to other functions and computations parts I don't want to time
    //
    start = high_resolution_clock::now();
    bar();
    stop = high_resolution_clock::now();
    auto duration_bar = duration_cast<seconds>(stop - start);
    cout << "time in bar: " << duration_bar.count() << endl;

    return 0;
}

void foo() { // a complex function
sleep(1);
}

void bar() { // another complex function
sleep(2);
}

I want the total time for each of the functions, for instance, for foo() it is 5 seconds, while now I always get 1 second. The number of iterations is known only at runtime (n=5 here is fixed just for simplicity).

To compute the total time for each of the functions I did try replacing the type above by using static and accumulate the results but didn't work.

CodePudding user response:

You can use some container to store the times, pass it by reference and accumulate the times. For example with a std::map<std::string,unsinged> to have labels:

int recursive(int n, std::map<std::string,unsigned>& times) { 
    if (n >= 0) return;
    // measure time of foo
    times["foo"]  = duration_foo;
    // measure time of bar
    times["bar"]  = duration_bar;
    // recurse
    recursive(n-1,times);
}

Then

std::map<std::string,unsigned> times;
recursive(200,times);
for (const auto& t : times) {
    std::cout << t.first << " took total : " << t.second << "\n";
}
  • Related