Optimize trace flushing.

Rather than flushing at every function exit, we only
flush when the call stack is almost empty.