Commit 24c9af1
authored
⚡️ Speed up function
Here’s your optimized program, rewritten for maximal speed and reduced memory use.
**Key optimizations:**
1. **Replace O(N) loop for summing with a direct formula** (`k = sum(range(number * 100)) == (n-1)*n/2`): replaces explicit iteration with a pure arithmetic expression—much faster.
2. **Use f-string and list comprehension for str join** (more efficient than generator expressions in CPython, better than repeated calls).
3. Avoid unnecessary assignments and keep only results relevant for function output if required, but per your request, we must keep the function return unchanged.
Optimized code.
### Notes.
- The core bottleneck was the explicit `for`-loop for summing, replaced by the direct formula.
- `" ".join(str(i) for i in range(number))` is very slightly slower than `.join([str(i) for i in range(number)])` in most versions of CPython for large numbers, due to generator overhead.
- Memory use for `join` is `O(n)` in all cases, but the rest of the function is now minimal.
This should **greatly reduce the runtime** (from hundreds of ms to a small fraction), as almost all the time was being spent in the explicit for-loops.funcA by 4,113%1 parent 62efaf7 commit 24c9af1
File tree
1 file changed
+10
-8
lines changed- code_to_optimize/code_directories/simple_tracer_e2e
1 file changed
+10
-8
lines changedLines changed: 10 additions & 8 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
3 | 3 | | |
4 | 4 | | |
5 | 5 | | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
10 | | - | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
11 | 9 | | |
12 | | - | |
13 | | - | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
14 | 15 | | |
15 | 16 | | |
16 | 17 | | |
| |||
42 | 43 | | |
43 | 44 | | |
44 | 45 | | |
45 | | - | |
| 46 | + | |
| 47 | + | |
46 | 48 | | |
47 | 49 | | |
48 | 50 | | |
| |||
0 commit comments