My logging code uses the return value of backtrace() to determine the current stack depth (for pretty printing purposes), but I can see from profiling that this is a pretty expensive call.
I don’t suppose there’s a cheaper way of doing this? Note that I don’t care about the frame addresses, just how many of them there are.
edit: These logging functions are used all over a large code-base, so manually tracking the stack depth isn’t really an option.
Walking the stack yourself is pretty quick – most of the slowness in
backtrace()is from looking up symbol names. On x86, you can do the following:This will walk the chain of
ebppointers. Keep in mind that this is extremely non-portable. Also note that this will not count any functions which have been inlined or tail-call optimized (of course,backtrace()has the same problem).Another important issue is the termination condition — once you backtrace up to
main(), there often aren’t guarantees about what you’ll find in the stack. So, if libc doesn’t put a null frame pointer, you’ll very likely segfault. You can get the termination value by looking at it at the very beginning ofmain().