This guide explains how to set up a Python environment, configure VSCode, and measure time and space complexity for your project. It includes a decorator for automatic time and memory profiling for future use.
- 1. Setting Up a Virtual Environment
- 2. Configuring VSCode with the Virtual Environment
- 3. Measuring Time and Space Complexity
- 4. Automatic Time and Space Profiling with a Decorator
Install virtualenv
if it's not already installed:
pip install virtualenv
Create a virtual environment for your project:
virtualenv venv
Replace venv
with the desired name for your environment.
Activate the environment:
- On Windows:
.\venv\Scripts\activate
- On macOS/Linux:
source venv/bin/activate
When done, deactivate the environment:
deactivate
Launch VSCode and open your project folder.
- Press
Ctrl + Shift + P
to open the command palette. - Type
Python: Select Interpreter
and select the virtual environment you created (env_name
).
This ensures VSCode uses the correct Python environment for running your code.
To measure the time complexity of a function, use Python’s time
module:
import time
def example_function():
start_time = time.time()
# A dummy function to simulate processing
return sum([i ** 2 for i in range(n)])
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
To measure memory usage, use the memory-profiler
library.
pip install memory-profiler
Apply the @profile
decorator to your function:
from memory_profiler import profile
@profile
def example_function():
# A dummy function to simulate processing
return sum([i ** 2 for i in range(n)])
Run the script using:
python -m memory_profiler your_script.py
To automatically measure time and space complexity in your next project, use this custom decorator:
from memory_profiler import memory_usage
import time
def time_and_space_profiler(func):
def wrapper(*args, **kwargs):
start_time = time.time()
mem_before = memory_usage()[0]
result = func(*args, **kwargs)
mem_after = memory_usage()[0]
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
print(f"Memory usage: {mem_after - mem_before} MiB")
return result
return wrapper
# Example usage:
@time_and_space_profiler
def example_function():
# A dummy function to simulate processing
return sum([i ** 2 for i in range(n)])
# Test the decorator
example_function(1000000)
This decorator can be applied to any function to automatically report time and memory usage when the function is run.
In your upcoming projects, you will use the above setup and tools to work efficiently with Python and measure both time and space complexity of your code. Happy coding!