Skip to content

Commit a10b0a2

Browse files
⚡️ Speed up function funcA by 3,893%
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!
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 changed

code_to_optimize/code_directories/simple_tracer_e2e/workload.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33

44
def funcA(number):
55
number = min(1000, number)
6-
k = 0
7-
for i in range(number * 100):
8-
k += i
9-
# Simplify the for loop by using sum with a range object
10-
j = sum(range(number))
11-
12-
# Use a generator expression directly in join for more efficiency
13-
return " ".join(str(i) for i in range(number))
6+
# Replace the for loop with direct formula for arithmetic sum
7+
k = (number * 100) * (number * 100 - 1) // 2
8+
9+
# Simplify the for loop by using arithmetic series sum formula
10+
j = number * (number - 1) // 2
11+
12+
# Use map(str, ...) instead of generator expr in join for improved efficiency
13+
return " ".join(map(str, range(number)))
1414

1515

1616
def test_threadpool() -> None:

0 commit comments

Comments
 (0)