Skip to content

Commit 2dfaaab

Browse files
authored
Merge pull request #21 from JostMigenda/execution-time
add execution time output to example codes
2 parents 7f1fd2c + fd061a6 commit 2dfaaab

File tree

3 files changed

+24
-6
lines changed

3 files changed

+24
-6
lines changed

episodes/files/bubblesort/bubblesort.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
1-
import sys
21
import random
2+
import sys
3+
import time
34

45
# Argument parsing
56
if len(sys.argv) != 2:
67
print("Script expects 1 positive integer argument, %u found."%(len(sys.argv) - 1))
78
sys.exit()
89
n = int(sys.argv[1])
10+
911
# Init
1012
random.seed(12)
1113
arr = [random.random() for i in range(n)]
1214
print("Sorting %d elements"%(n))
15+
start_time = time.monotonic()
16+
1317
# Sort
1418
for i in range(n - 1):
1519
swapped = False
@@ -20,9 +24,13 @@
2024
# If no two elements were swapped in the inner loop, the array is sorted
2125
if not swapped:
2226
break
27+
28+
end_time = time.monotonic()
29+
2330
# Validate
2431
is_sorted = True
2532
for i in range(n - 1):
2633
if arr[i] > arr[i+1]:
2734
is_sorted = False
28-
print("Sorting: %s"%("Passed" if is_sorted else "Failed"))
35+
36+
print(f"Sorting: {'Passed' if is_sorted else 'Failed'} in {end_time - start_time:.3f} s")

episodes/files/pred-prey/predprey.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
import sys
21
import math
3-
import numpy as np
2+
import sys
3+
import time
4+
45
import matplotlib.pyplot as plt
6+
import numpy as np
57

68
# Reproduction
79
REPRODUCE_PREY_PROB = 0.05
@@ -424,6 +426,9 @@ def run(self, random_seed=12):
424426
if steps < 1:
425427
print("Script expects 1 positive integer argument (number of steps), %s converts < 1."%(sys.argv[1]))
426428
sys.exit(1)
427-
429+
430+
start_time = time.monotonic()
428431
model = Model(steps=steps)
429-
model.run()
432+
model.run()
433+
end_time = time.monotonic()
434+
print(f"Execution time: {end_time - start_time:.3f} s")

episodes/files/travelling-sales/travellingsales.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import math
88
import random
99
import sys
10+
import time
1011

1112
def distance(point1, point2):
1213
return math.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2)
@@ -42,7 +43,11 @@ def traveling_salesman_brute_force(points):
4243
cities.append((random.uniform(-1, 1), random.uniform(-1, 1)))
4344

4445
# Find the shortest path
46+
start_time = time.monotonic()
4547
shortest_path, min_distance = traveling_salesman_brute_force(cities)
48+
end_time = time.monotonic()
49+
4650
print("Cities:", cities_len)
4751
print("Shortest Path:", shortest_path)
4852
print("Shortest Distance:", min_distance)
53+
print(f"Execution time: {end_time - start_time:.3f} s")

0 commit comments

Comments
 (0)