Created
March 5, 2014 18:07
-
-
Save schnittstabil/9372911 to your computer and use it in GitHub Desktop.
logging.isEnabledFor vs lazyjoin class benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
logging.basicConfig(level=logging.INFO) | |
logger = logging.getLogger("log") | |
def simple(): | |
if logger.isEnabledFor(logging.DEBUG): | |
logger.debug( | |
'Stupid log message ' + ' '.join([str(i) for i in range(20)]) | |
) | |
# Do something | |
class lazyjoin: | |
def __init__(self, s, items): | |
self.s = s | |
self.items = items | |
def __str__(self): | |
return self.s.join(self.items) | |
def lazy(): | |
logger.debug( | |
'Stupid log message %s', lazyjoin(' ', (str(i) for i in range(20))) | |
) | |
# Do something | |
if __name__ == '__main__': | |
import timeit | |
print(min(timeit.repeat("simple()", setup="from __main__ import simple"))) | |
print(min(timeit.repeat("lazy()", setup="from __main__ import lazy"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@guyarad You're ignoring the time needed to create the
lazyjoin
instancelazy_log
:For a real world scenario you have to measure that time too.
At the time of writing my stackoverflow answer,
logger.isEnabledFor(logging.DEBUG)
was 4 times faster than creating alazyjoin
instance.See also my stackoverflow answer to Python: how to do lazy debug logging.
Nevertheless, even in your scenario, I see no need to create those expensive
LazyLogging
instances.Instead you could use a simple and efficient
lazy_debug
function:If you want to improve this, you may extend the logger class with a
lazy_debug
method, which is hard though, IIRC.