I would like to use scope guard in C in order to do profiling.
I would like to know how much time I spend in a function. Here is what I do:
int function() {
tic();
... do stuff ...
if (something)
{
toc();
return 0;
}
toc();
return 1;
}
I need to place a toc statement each time I exit the function. I would like to do that without having to copy paste toc everywhere. Is there a generic way to do that, using a macro or something ? Also I don't want to change the way the function is called, as there are many functions I have to profile.
Thanks
This doesn't change the way the function is called. Probably not much use if you want to be able to profile every single function, though.
static inline int real_function() {
// previous contents of function(), with no tic or toc
}
int function() {
tic();
int r = real_function();
toc();
return r;
}
As everyone else says: use a profiler, it will save you a lot of effort in the long run. As they don't say: if your platform has one.
If it doesn't, then the easiest might be to say (as a coding rule) that functions must have only one exit point, and that exit point must be via your macro. Then you can manually instrument all your functions with code at entry and exit. Legacy functions with multiple returns can be wrapped up as above.
Also, bear in mind when you're doing anything like this that your compiler can mess you up. You might write this:
tic();
do_something();
int i = something_else();
toc();
return i;
If the compiler determines that something_else has no side-effects, then even though something_else takes significant time, it might turn the code into this:
tic();
do_something();
toc();
return something_else();
And your profile data will under-estimate the time spent in your function. Another reason it's so good to have a real profiler - it can co-operate with the compiler.
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