script_12.py - List Performance
Code
See script_12.py for full code.
Explanation
Line 8: import time
- time module for measuring execution time
Line 9: from collections import deque
- deque for performance comparison
Line 11-15: def time_operation(func, *args):
- *args captures variable number of arguments as tuple
- Function takes another function as parameter (higher-order function)
Line 12: start = time.time()
- .time() returns float (seconds since epoch)
- High precision timestamp
Line 13: result = func(*args)
- *args unpacks tuple into separate arguments
- Calls the function passed as parameter
- Executes the operation being timed
Line 14: end = time.time()
- Second timestamp after operation
Line 15: return result, (end - start) * 1000
- Subtracts timestamps to get duration
- * 1000 converts seconds to milliseconds
- Returns tuple: (result, time_in_ms)
Line 22: test_list = list(range(n))
- Creates list with n elements
- range(n) is 0 to n-1
Line 23: test_deque = deque(range(n))
- Creates deque with same elements
- Different internal structure
Line 28: def remove_from_list_front(lst, times):
- Function to benchmark list.pop(0)
Line 30: lst.pop(0)
- Removes from front of list
- O(n) complexity - must shift all remaining elements
- Slow for large lists
Line 36: dq.popleft()
- Removes from front of deque
- O(1) complexity - constant time
- Much faster than list.pop(0)
Line 45: return 9999 in lst
- in operator for lists
- O(n) complexity - must check each element linearly
Line 48: return 9999 in s
- in operator for sets
- O(1) average complexity - hash lookup
- Much faster than list membership test