-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmatrix_chain_order.py
More file actions
46 lines (37 loc) · 1.47 KB
/
matrix_chain_order.py
File metadata and controls
46 lines (37 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import numpy as np
import time
import psutil
def matrix_chain_order(p, i, j):
if i == j:
return 0
min_cost = float('inf')
for k in range(i, j):
count = (matrix_chain_order(p, i, k) +
matrix_chain_order(p, k + 1, j) +
p[i-1] * p[k] * p[j])
if count < min_cost:
min_cost = count
return min_cost
def measure_execution_time_and_memory(func, *args, **kwargs):
"""
Measures the execution time and memory usage of a passed function.
"""
process = psutil.Process()
start_time = time.time()
start_memory = process.memory_info().rss # Memory usage before execution
result = func(*args, **kwargs) # Execute the function
end_memory = process.memory_info().rss # Memory usage after execution
end_time = time.time()
execution_time = end_time - start_time # Total execution time
memory_usage = end_memory - start_memory # Total memory used
print(f"Result: {result}")
print(f"Execution Time: {execution_time:.4f} seconds")
print(f"Memory Usage: {memory_usage} bytes, approximately {memory_usage / 1024 ** 2:.2f} MB")
def main():
# Generate random integers for matrix dimensions (more appropriate than floating-point)
arr = np.random.randint(2, 100, size=20)
n = len(arr)
# Measuring the matrix chain multiplication function
measure_execution_time_and_memory(matrix_chain_order, arr, 1, n-1)
if __name__ == "__main__":
main()