Skip to content

Commit 3b06a1b

Browse files
⚡️ Speed up function funcA by 17%
Here’s an optimized version of your code. The overwhelming majority of time is spent joining and converting numbers to strings (the line with `" ".join(map(str, range(number)))`). Python's core string join and `str` are already highly optimized, but for further speedup, we can reduce the number of temporary string objects created during joining. **Preallocating** and using a list comprehension to convert numbers to strings, and then joining, is marginally faster for large numbers. On Python 3.6+ (as in your version), using `str(i)` is reliable, but using f-strings with list comprehensions is slightly faster. You may also use the [array module](https://docs.python.org/3/library/array.html), but for string conversion, it's generally not faster. We will also eliminate unnecessary calculations as their results are not used. Here's the faster version. ### Notes on the rewrite. - The preallocated list comprehension with f-strings is faster than `map(str, ...)` in this context according to microbenchmarks. - Removing the unnecessary variable calculations reduces wasted CPU. - If extremely high speed is required and the input `number` is always relatively small (up to 1000), you could also precompute all possible outputs and index into the result, at the cost of memory—you can ask for that version if needed. **Summary**: The optimization here is mostly removing dead code and making string conversion and joining as fast as Python allows. For huge scale, alternative approaches (precomputing, C extensions) would be needed, but for your requirements, this is the fastest pure Python code. Let me know if you want advanced (Cython or memcpy) solutions!
1 parent 2a3f344 commit 3b06a1b

File tree

1 file changed

+3
-8
lines changed
  • code_to_optimize/code_directories/simple_tracer_e2e

1 file changed

+3
-8
lines changed

code_to_optimize/code_directories/simple_tracer_e2e/workload.py

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

44
def funcA(number):
55
number = min(1000, number)
6-
# Use direct formula for sum of 0 to number*100-1
7-
total_terms = number * 100
8-
k = total_terms * (total_terms - 1) // 2
6+
# Removed unnecessary calculations of total_terms, k, j, as they are never used
97

10-
# Use direct formula for sum of 0 to number-1
11-
j = number * (number - 1) // 2
12-
13-
# Use map(str, ...) which is faster than generator expression
14-
return " ".join(map(str, range(number)))
8+
# Use a list comprehension with f-strings, which is slightly faster than map(str, ...)
9+
return " ".join([f"{i}" for i in range(number)])
1510

1611

1712
def test_threadpool() -> None:

0 commit comments

Comments
 (0)