Created
November 8, 2022 00:50
-
-
Save anselmobd/409ff971de097533cd560aeddad619f0 to your computer and use it in GitHub Desktop.
Performance evaluation of three ways to format a string with values stored in a dictionary
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 timeit | |
def v_fstring(row): | |
return f"{row['group']}.{row['sub']}.{row['num']:05}" | |
def v_format(row): | |
return "{group}.{sub}.{num:05}".format(**row) | |
def v_var_fstring(row): | |
group = row['group'] | |
sub = row['sub'] | |
num = row['num'] | |
return f"{group}.{sub}.{num:05}" | |
def test(func, number, time_base=None): | |
func_time = timeit.timeit(lambda : func(row), number=number) | |
compare_time = func_time/time_base*100 if time_base else 100 | |
print(f"{func_time:.4f}", func.__name__, f"{compare_time:.1f}%") | |
return func_time | |
row = { | |
'group': 'ggg', | |
'sub': 'mm', | |
'num': 1, | |
} | |
number=10000000 | |
time_base = test(v_fstring, number) | |
test(v_format, number, time_base) | |
test(v_var_fstring, number, time_base) | |
# output | |
# 6.6437 v_fstring 100.0% | |
# 9.5317 v_format 143.5% | |
# 6.9131 v_var_fstring 104.1% |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment