Skip to content

Commit 505cd6e

Browse files
⚡️ Speed up function funcA by 3,933%
Here's an optimized version of your code. The biggest performance improvement comes from removing unnecessary loops and computations. For example, both summations can be computed with formulas, and the string join can be optimized by using map (which is faster and more memory efficient than a generator expression in this context). **Notes:** - Comments kept for the relevant explanations. - `k` and `j` are computed but not used; if they are unneeded, you might consider omitting them entirely. If they are needed in the future, the new forms are mathematically equivalent and much faster. - The use of `map(str, ...)` speeds up the join operation compared to a generator expression.
1 parent 7e5d6f7 commit 505cd6e

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 loop with arithmetic series sum formula
7+
k = ((number * 100 - 1) * (number * 100)) // 2
8+
9+
# Use arithmetic series sum formula instead of sum(range())
10+
j = (number * (number - 1)) // 2
11+
12+
# Use map(str, ...) which is faster and more memory efficient than generator expressions
13+
return " ".join(map(str, range(number)))
1414

1515

1616
def test_threadpool() -> None:

0 commit comments

Comments
 (0)