Skip to content

Instantly share code, notes, and snippets.

@ipmb
Last active November 14, 2017 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ipmb/42adbb26e3e6a797a493a003cfdca428 to your computer and use it in GitHub Desktop.
Save ipmb/42adbb26e3e6a797a493a003cfdca428 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""Example of the speed-up allowed by logging's string handling"""
from __future__ import division
import logging
import string
import time
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)
# make a big object that is slow to turn into a string
big_obj = {}
obj = big_obj
for x in string.ascii_letters * 1000:
obj[x] = {}
obj = obj[x]
def time_log(level):
start = time.time()
getattr(logger, level)('%s: This is a big object: %s', level, big_obj)
end = time.time()
return end - start
# this is not logged
ignored_log = time_log('debug')
# this is logged
logged_log = time_log('info')
print("""
unlogged time: {}s
logged time: {}s
unlogged time is {:.0f}x faster
""".format(ignored_log, logged_log, logged_log / ignored_log))
unlogged time: 3.0040740966796875e-05s
logged time: 1.5769679546356201s
unlogged time is 52494x faster
@yml
Copy link

yml commented Nov 14, 2017

Seg fault!!!

yml@kodi$ python --version
Python 3.5.3
(test_logging) ~/Dropbox/Devs/python/test_logging (no branch)
yml@kodi$ python log_string_formatting.py
Segmentation fault (core dumped)
(test_logging) ~/Dropbox/Devs/python/test_logging (no branch)
yml@kodi$ cat log_string_formatting.py
"""Example of the speed-up allowed by logging's string handling"""
from __future__ import division
import logging
import string
import time

logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)

# make a big object that is slow to turn into a string
big_obj = {}
obj = big_obj
for x in string.ascii_letters * 1000:
    obj[x] = {}
    obj = obj[x]


def time_log(level):
    start = time.time()
    getattr(logger, level)('%s: This is a big object: %s', level, big_obj)
    end = time.time()
    return end - start


# this is not logged
ignored_log = time_log('debug')
# this is logged
logged_log = time_log('info')

print("""
unlogged time: {}s
logged time: {}s
unlogged time is {:.0f}x faster
""".format(ignored_log, logged_log, logged_log / ignored_log))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment