Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have matlab tic toc in C++?

Tags:

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
like image 822
Mohammad Moghimi Avatar asked Nov 21 '12 02:11

Mohammad Moghimi


2 Answers

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;
}
like image 196
Xymostech Avatar answered Sep 22 '22 10:09

Xymostech


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.

like image 41
John3136 Avatar answered Sep 24 '22 10:09

John3136