Created
October 19, 2023 16:04
-
-
Save ksuderman/dd1c47d2223f13bed4551615690071ab to your computer and use it in GitHub Desktop.
Compare greedy vs lazy string interpolation in log messages
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
# A simple timing test to compare lazy and greedy string interpolation | |
# in log messages | |
import timeit | |
# Debug messages will not be logged | |
SETUP = ''' | |
import logging | |
logging.basicConfig(level=logging.WARNING) | |
log = logging.getLogger("mylogger") | |
fvalue = 3.14 | |
ivalue = 1 | |
svalue = 'Hello world' | |
''' | |
# Logging with f-strings (greedy string interpolation) | |
greedy_logging = ''' | |
log.info(f'fstring float value {fvalue:2.3f} int value {ivalue:03} string value {svalue:>20}') | |
''' | |
# Lazy string interpolation | |
lazy_logging = ''' | |
log.info('percent float value %2.3f int value %03d string value "%20s", fvalue, ivalue, svalue') | |
''' | |
if __name__ == '__main__': | |
n = 1000000 | |
t_greedy = timeit.timeit(greedy_logging, setup=SETUP, number=n) | |
t_lazy = timeit.timeit(lazy_logging, setup=SETUP, number=n) | |
print(f'Greedy: {t_greedy}') | |
print(f'Lazy : {t_lazy}') | |
print(f'greedy / lazy = {t_greedy*100/t_lazy:3.2f}%') | |
print(f'lazy / greedy = {t_lazy*100/t_greedy:3.2f}%') | |
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
Greedy: 0.918115834 | |
Lazy : 0.22738941700000004 | |
greedy / lazy = 403.76% | |
lazy / greedy = 24.77% |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment