Creating custom modules in Python - Performance & Efficiency
When we create custom modules in Python, we want to know how the time it takes to run our code changes as our program grows.
We ask: how does using a module affect the speed of our program as it gets bigger?
Analyze the time complexity of the following code snippet.
# custom_module.py
def greet(name):
return f"Hello, {name}!"
# main.py
import custom_module
users = ["Alice", "Bob", "Charlie"] # Example list of users
for user in users:
print(custom_module.greet(user))
This code imports a custom module with a simple function and calls it once for each user in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the greet function inside a loop over the users list.
- How many times: Once for each user in the list.
Each time we add more users, the program calls the greet function more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greet calls |
| 100 | 100 greet calls |
| 1000 | 1000 greet calls |
Pattern observation: The number of operations grows directly with the number of users.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of users grows.
[X] Wrong: "Importing a module makes the program slower every time I call its functions."
[OK] Correct: Importing happens once at the start; calling functions inside loops is what grows with input size.
Understanding how your code runs when using modules helps you write clear and efficient programs, a skill valued in many coding challenges and real projects.
"What if the greet function itself had a loop over a list of greetings? How would the time complexity change?"