CodeBlanks Logo Icon CodeBlanks

Summary - Performance

Combine timeit, cProfile and __slots__ to write an optimized handler.

Recap: Performance

In this group you learned Python performance tools. You measured with timeit and profiled with cProfile.

You measured memory with sys.getsizeof. You saved memory with __slots__. You applied vectorization with numpy. Now you will combine these into an optimized handler: a memory-friendly class with __slots__ and fast computation with numpy together.

Practice Write an optimized handler

Import the module with import numpy as np. Write a Point class with __slots__ = ['data']. In __init__(self, data) set self.data = np.array(data). Add a squared method returning self.data ** 2. Create a Point([1, 2, 3]) instance and print .squared().

Starter code

main.py
# write the Point class: slots + numpy
# create an instance and print

Sample solution

main.py
import numpy as np

class Point:
    __slots__ = ["data"]
    def __init__(self, data):
        self.data = np.array(data)
    def squared(self):
        return self.data ** 2

p = Point([1, 2, 3])
print(p.squared())

Expected output

[1 4 9]

What you learned

In this group you learned Python performance optimization. You measured with timeit and profiled with cProfile. You measured memory with sys.getsizeof.

You saved memory with __slots__ and applied vectorization with numpy. In the summary you combined these into an optimized handler. This knowledge is critical for large-data and high-performance applications.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which tool for which job?

  • timeit to measure memory
  • getsizeof for vectorization
  • cProfile for time profiling Correct answer
  • numpy for profiling

Explanation: cProfile profiles function times. The other matches are wrong.

2 Match all performance concepts

Term Meaning
timeit Measures time
cProfile Profiles
getsizeof Measures memory
numpy Vectorizes

3 Final blank

Question
import numpy as ____
a = np.array([1, 2, 3])
Answer
import numpy as np
a = np.array([1, 2, 3])

Explanation: import numpy as np is the standard alias.

All lessons in Expert