Reprinted form: https://*.com/questions/13485266/how-to-have-matlab-tic-toc-in-c/13485583#13485583
in matlab:
tic
do something ...
toc
How I can do this in C++?
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 ;
}