Commit a10b0a2
authored
⚡️ Speed up function
Let's identify and target the main performance bottlenecks from the line profiler.
#### Bottlenecks
1. **for i in range(number * 100): k += i**
- 99%+ of the function runtime is spent here.
- This loop is just summing numbers from 0 to (number*100 - 1), i.e. it's arithmetic series summation. This can be replaced with a formula for O(1) computation.
2. **return " ".join(str(i) for i in range(number))**
- Making many temporary strings and generator expressions per call of `str(i)`.
- Use `map(str, ...)` instead of generator expression. This is slightly faster since `str` is a built-in and `map` is optimized.
3. **sum(range(number))**
- Can be replaced with a formula as well.
#### Modified code with comments preserved and changes documented.
**What changed:**
- Replaced the O(N) summing in both the manual loop and `sum` with O(1) arithmetic formula.
- Used built-in `map` for string conversion before joining.
**Performance gain:**
This will eliminate nearly all of the CPU time from the hot loops, making the running time extremely short except for the join operation, which is now as fast as possible. The output and all variable assignments (k, j, returned string) remain exactly as before.
Let me know if you want precise microbenchmark figures!funcA by 3,893%1 parent f7c494a commit a10b0a2
File tree
1 file changed
+8
-8
lines changed- code_to_optimize/code_directories/simple_tracer_e2e
1 file changed
+8
-8
lines changedLines changed: 8 additions & 8 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
3 | 3 | | |
4 | 4 | | |
5 | 5 | | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
10 | | - | |
11 | | - | |
12 | | - | |
13 | | - | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
14 | 14 | | |
15 | 15 | | |
16 | 16 | | |
| |||
0 commit comments