Skip to content

Commit 7e5d6f7

Browse files
⚡️ Speed up method SimpleModel.predict by 9,155,806%
Here is an optimized version of your program. The main bottlenecks were. - The `sleep(10)` call was likely used for simulation, but if you want faster execution, it should be removed or reduced. - The nested loop (`for i in range(500)` over `for x in data`) repeatedly calculates the same value for `x * i**2` and accumulates in `computation`, but `computation` is always just `x * i**2` because it's initialized to 0 each iteration. - Precomputing values and using list comprehensions speeds up execution significantly. Optimized code. **Changes made:** - Removed or commented out `sleep(10)`. - Precomputed `i**2` to avoid recalculating it. - Eliminated unnecessary variable and reduced loop nesting overhead. This will run **much** faster while returning the same value as the original.
1 parent 67bd717 commit 7e5d6f7

File tree

1 file changed

+11
-9
lines changed
  • code_to_optimize/code_directories/simple_tracer_e2e

1 file changed

+11
-9
lines changed

code_to_optimize/code_directories/simple_tracer_e2e/workload.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
from concurrent.futures import ThreadPoolExecutor
2-
from time import sleep
32

43

54
def funcA(number):
6-
number = number if number < 1000 else 1000
5+
number = min(1000, number)
76
k = 0
87
for i in range(number * 100):
98
k += i
@@ -22,14 +21,15 @@ def test_threadpool() -> None:
2221
for r in result:
2322
print(r)
2423

24+
2525
class AlexNet:
2626
def __init__(self, num_classes=1000):
2727
self.num_classes = num_classes
2828
self.features_size = 256 * 6 * 6
2929

3030
def forward(self, x):
3131
features = self._extract_features(x)
32-
32+
3333
output = self._classify(features)
3434
return output
3535

@@ -44,18 +44,19 @@ def _classify(self, features):
4444
total = sum(features)
4545
return [total % self.num_classes for _ in features]
4646

47+
4748
class SimpleModel:
4849
@staticmethod
4950
def predict(data):
5051
result = []
51-
sleep(10)
52-
for i in range(500):
52+
# sleep(10) # Commented out for better performance
53+
i_squares = [i * i for i in range(500)]
54+
# Precompute x * i**2 for all combinations
55+
for i_sq in i_squares:
5356
for x in data:
54-
computation = 0
55-
computation += x * i ** 2
56-
result.append(computation)
57+
result.append(x * i_sq)
5758
return result
58-
59+
5960
@classmethod
6061
def create_default(cls):
6162
return cls()
@@ -69,6 +70,7 @@ def test_models():
6970
model2 = SimpleModel.create_default()
7071
prediction = model2.predict(input_data)
7172

73+
7274
if __name__ == "__main__":
7375
test_threadpool()
7476
test_models()

0 commit comments

Comments
 (0)