Skip to content

Latest commit

 

History

History
27 lines (19 loc) · 737 Bytes

20240726111622.md

File metadata and controls

27 lines (19 loc) · 737 Bytes

Timing code in Python

Using timeit to compare merging dictionaries in #Python: Old way with ** unpacking vs. new way with |.

timeit runs the code 1000 times, using globals to pass variables, and prints the timing results:

import timeit

dict1 = {f'key{i}': i for i in range(10000)}
dict2 = {f'key{i}': i for i in range(5000, 15000)}

old_way_time = timeit.timeit('''
merged_dict = {**dict1, **dict2}
''', globals=globals(), number=1000)

new_way_time = timeit.timeit('''
merged_dict = dict1 | dict2
''', globals=globals(), number=1000)

print(f"Old way time: {old_way_time:.6f} seconds")
print(f"New way time: {new_way_time:.6f} seconds")
# Old way time: 0.222962 seconds
# New way time: 0.222384 seconds

#timeit