Mohammad Moghimi
Mohammad Moghimi

Reputation: 4686

How to have matlab tic toc in C++?

in matlab:

tic
do something ...
toc

my attempt to have this functionality:

#define tic      double tic_t = clock();
#define toc      std::cout << (clock() - tic_t)/CLOCKS_PER_SEC \
                           << " seconds" << std::endl;

Now I can do this in C++:

tic
doSomething();
toc

The problem is that I cannot call it multiple times inside a function because tic_t will be defined several times. I want to do something like this:

tic
doSomething1();
toc
tic
doSomething2();
toc

Upvotes: 5

Views: 7515

Answers (2)

Xymostech
Xymostech

Reputation: 9850

I'd implement it as a stack. Then, you can recurse, call it multiple times, do whatever you want, and it won't break, so long as you call toc() after every tic(). As a bonus, you don't have to resort to using macros:

#include <iostream>
#include <stack>
#include <ctime>

std::stack<clock_t> tictoc_stack;

void tic() {
    tictoc_stack.push(clock());
}

void toc() {
    std::cout << "Time elapsed: "
              << ((double)(clock() - tictoc_stack.top())) / CLOCKS_PER_SEC
              << std::endl;
    tictoc_stack.pop();
}

int main(int argc, char *argv[]) {
    tic();
    doSomething();
    toc();
    return 0;
}

Upvotes: 18

John3136
John3136

Reputation: 29265

Either put double tic_t; as a global, and #define tic tic_t = clock(); or add a #define tictoc_init double tic_t that you use at the top of each method (and change tic as above)

The second way is better since "doSomething()" may contain tics and tocs that would overwrite your global variable.

Upvotes: 2

Related Questions