Skip to content

Commit

Permalink
new tip, slight edit on another one
Browse files Browse the repository at this point in the history
  • Loading branch information
bbelderbos committed Jul 26, 2024
1 parent 234c626 commit ddb56ae
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
4 changes: 4 additions & 0 deletions index.md
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,10 @@ This file gets generated by [this script](index.py).

- [Faster page downloads](notes/20230110130247.md)

## Timeit

- [Timing code in python](notes/20240726111622.md)

## Tips'])

- [Dataclass with extra construction](notes/20240223145038.md)
Expand Down
2 changes: 1 addition & 1 deletion notes/20240726111223.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# You can now use | for typing

`|` got added to type hints >= 3.10, not needing the `typing` import anymore:
`|` got added to type hints >= 3.10, not needing the `typing` import anymore for these:

- Unions can now be written as `X | Y`
- Optional can now be written as `X | None`
Expand Down
27 changes: 27 additions & 0 deletions notes/20240726111622.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# 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

0 comments on commit ddb56ae

Please sign in to comment.