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
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With