Commit dac1054
authored
⚡️ Speed up function
Let's analyze the performance issues as highlighted by the profiler.
- The `for i in range(number * 100): k += i` loop takes over **99%** of the time.
- The `" ".join(str(i) for i in range(number))` uses a generator expression, but for larger `number` values, repeated string concatenations are costly.
- The sum using `sum(range(number))` is much faster than the loop, but can be replaced with a direct formula for further speed.
Let's **optimize**.
1. **Replace the sum loop** `for i in range(number * 100): k += i` with the arithmetic series formula: `sum_{i=0}^{n-1} i = n*(n-1)//2`.
2. The `" ".join(...)` part is already efficient. However, since `str.join()` collections can be much faster on prebuilt lists than generators for larger numbers, let's use a list comprehension there.
Here's your rewritten code, optimized for speed.
**Why is it faster?**
- The O(N) loop is replaced with O(1) math.
- The `" ".join(list)` is slightly faster than with a generator for this use.
- All preserved logic and return value.
**Comments are updated** to reflect optimizations. Existing comments on sum simplification and generator usage have been updated according to the new relevant code sections.
Let me know if you need further memory optimizations (eg. generate directly as iterable for huge numbers, or apply similar changes elsewhere)!funcA by 3,905%1 parent 059b4dc commit dac1054
File tree
1 file changed
+22
-12
lines changed- code_to_optimize/code_directories/simple_tracer_e2e
1 file changed
+22
-12
lines changedLines changed: 22 additions & 12 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
| 2 | + | |
2 | 3 | | |
3 | 4 | | |
4 | 5 | | |
5 | | - | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
10 | | - | |
11 | | - | |
12 | | - | |
13 | | - | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
14 | 13 | | |
15 | 14 | | |
16 | 15 | | |
| |||
21 | 20 | | |
22 | 21 | | |
23 | 22 | | |
| 23 | + | |
24 | 24 | | |
25 | 25 | | |
26 | 26 | | |
27 | 27 | | |
28 | 28 | | |
29 | 29 | | |
30 | 30 | | |
31 | | - | |
| 31 | + | |
32 | 32 | | |
33 | 33 | | |
34 | 34 | | |
| |||
43 | 43 | | |
44 | 44 | | |
45 | 45 | | |
| 46 | + | |
46 | 47 | | |
47 | 48 | | |
48 | 49 | | |
49 | | - | |
50 | | - | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
51 | 59 | | |
52 | 60 | | |
53 | 61 | | |
54 | 62 | | |
| 63 | + | |
55 | 64 | | |
56 | 65 | | |
57 | 66 | | |
| |||
60 | 69 | | |
61 | 70 | | |
62 | 71 | | |
| 72 | + | |
63 | 73 | | |
64 | 74 | | |
65 | 75 | | |
0 commit comments