Skip to content

Commit 2a34cc0

Browse files
⚡️ Speed up function funcA by 15%
Here’s an optimized version of your code for Python 3.11.6. The main points of improvement are. - Replace `" ".join(str(i) for i in range(number))` with a faster approach that avoids repeated calls to `str(i)`. Using `map(str, ...)` is significantly faster and uses less overhead. - Since `j` is not used, you can remove its assignment to avoid unnecessary computation. - You don't need `min` every time if your `_cached_joined` function is correct, but preserving it as per the original function logic for correctness on inputs >1000. - The lru_cache remains, as it's critical to performance for repeated calls. Here’s the optimized version. This program will run strictly faster, especially for large input values and repeated calls due to the combination of a faster string conversion and the efficient use of the cache.
1 parent d03a5f9 commit 2a34cc0

File tree

1 file changed

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

1 file changed

+7
-8
lines changed

code_to_optimize/code_directories/simple_tracer_e2e/workload.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,7 @@
44

55
def funcA(number):
66
number = min(1000, number)
7-
# j is not used (retained for parity)
8-
j = number * (number - 1) // 2
9-
10-
# Use cached version for repeated calls
7+
# j is not used (retained for parity in logic, but removed for speed)
118
return _cached_joined(number)
129

1310

@@ -39,8 +36,9 @@ def _extract_features(self, x):
3936
return result
4037

4138
def _classify(self, features):
42-
total = sum(features)
43-
return [total % self.num_classes for _ in features]
39+
# Compute the sum and modulo just once, then construct the result list efficiently
40+
mod_val = sum(features) % self.num_classes
41+
return [mod_val] * len(features)
4442

4543

4644
class SimpleModel:
@@ -62,9 +60,10 @@ def test_models():
6260
prediction = model2.predict(input_data)
6361

6462

65-
@lru_cache(maxsize=1001) # One possible input per [0, 1000]
63+
@lru_cache(maxsize=1001)
6664
def _cached_joined(number):
67-
return " ".join(str(i) for i in range(number))
65+
# Use map(str, ...) instead of comprehension for better speed
66+
return " ".join(map(str, range(number)))
6867

6968

7069
if __name__ == "__main__":

0 commit comments

Comments
 (0)