-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort_time_measure.py
228 lines (185 loc) · 6.75 KB
/
sort_time_measure.py
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import random
import timeit
import statistics
import csv
# optional for plotting (figures already included)
import matplotlib.pyplot as plt
from sorting_algorithms import sorting
def measure_time(
algorithm: str, algorithm_stmt: str, array: list[int], n_repeats: int
) -> tuple[float, float]:
"""
Function for measuring time of the algorithm.
Args:
algorithm (str): Name of the algorithm.
algorithm_stmt (str): Statement of the algorithm (algorithm code).
array (list[int]): Array to sort.
n_repeats (int): Number of test repeats.
Returns:
mean_time (float): Mean time of the algorithm.
std_dev_time (float): Standard deviation of the algorithm.
"""
# Copy globals and add array to the local globals, this helps/ fixes issue where timeit cannot access the array
local_globals = globals().copy()
local_globals["array"] = array
# Measure time using timeit.repeat function
# stmt sets the statement (code) to be measured
# globals sets the global variables for the code
# number sets the number of executions of the code - imitate loop
# repeat sets the number of repeats - repeat should act like the previous run of code didn't happen
repeat_times = timeit.repeat(
stmt=algorithm_stmt, globals=local_globals, number=1, repeat=n_repeats
)
# Simple statistic calculation
mean_time = statistics.mean(repeat_times)
std_dev_time = statistics.stdev(repeat_times)
# Call private function to save measured time to a CSV file
_save_measured_time(
"sorting_time.csv", algorithm, len(array), mean_time, std_dev_time, n_repeats
)
return mean_time, std_dev_time
def _save_measured_time(
file_name: str,
algorithm: str,
array_size: int,
mean_time: float,
std_dev_time: float,
n_repeats: int,
) -> None:
"""
Save measured time to a CSV file.
Args:
file_name (str): Name of the CSV file.
algorithm (str): Name of the algorithm.
array_size (int): Size of the array.
mean_time (float): Mean time of the algorithm.
std_dev_time (float): Standard deviation of the algorithm.
n_repeats (int): Number of test repeats.
Returns:
None
"""
# Check if the file name has the correct extension
if not file_name.endswith(".csv"):
file_name += ".csv"
# Write the data to the CSV file
with open(file_name, "a", encoding="utf-8") as f:
row = [algorithm, array_size, mean_time, std_dev_time, n_repeats]
f.write(",".join(map(str, row)) + "\n")
def compare_algorithms(
algorithms: dict[str, str],
array: list[int],
n_repeats: int = 100,
) -> None:
"""
Function for comparing selected algorithms.
Args:
algorithms (dict[str, str]): Dictionary with algorithm names and statements.
array (list[int]): Array to sort.
n_repeats (int): Number of test repeats.
Returns:
None
"""
# Loop through the algorithms and measure the time
for algorithm, stmt in algorithms.items():
mean_time, std_dev_time = measure_time(
algorithm,
stmt,
array,
n_repeats,
)
print(
f"Algorithm: {algorithm}, Array size: {len(array)}, Mean time: {mean_time}, Standard deviation: {std_dev_time}"
)
def prepare_csv_file(name: str = "sorting_time.csv") -> None:
"""
Prepare CSV file for saving measured time. Write header to the file.
Args:
name (str): Name of the CSV file.
Returns:
None
"""
# Check if the file name has the correct extension
if not name.endswith(".csv"):
name += ".csv"
# Write the header to the CSV file
with open(name, "w", encoding="utf-8") as f:
header = [
"Algorithm",
"Array Size",
"Mean",
"Standard Deviation",
"Number of repeats",
]
f.write(",".join(header) + "\n")
def plot_algorithm_comparison(file_name: str = "sorting_time.csv") -> None:
"""
Function for plotting the comparison of sorting algorithms. Reads data from the CSV file. Saves the plot as a PNG file.
Args:
name (str): Name of the CSV file.
Returns:
None
"""
# prepare dictionary for storing data
times = {}
# Read data from the CSV file
with open(file_name, "r", encoding="utf-8") as f:
# Reader object in form of dictionary (header as keys)
reader = csv.DictReader(f)
for row in reader:
# Extract data from the row
name = row["Algorithm"]
n = int(row["Array Size"])
mean_time = float(row["Mean"])
std_dev_time = float(row["Standard Deviation"])
n_repeats = int(row["Number of repeats"])
# Check if the algorithm is already in the dictionary
if name not in times:
times[name] = {
"sizes": [],
"means": [],
"std_devs": [],
"n_repeats": [],
}
# Append data to the dictionary
times[name]["sizes"].append(n)
times[name]["means"].append(mean_time)
times[name]["std_devs"].append(std_dev_time)
times[name]["n_repeats"] = n_repeats
# Initialize the plot
plt.figure(figsize=(12, 8))
# Loop through the data for each algorithm and plot the results
for name, data in times.items():
sizes = data["sizes"]
means = data["means"]
std_devs = data["std_devs"]
# Calculate lower and upper bounds given by mean +- std_dev
# Used list comprehension, where zip function is used to iterate over multiple lists at the same time (create pairs of values - tuples)
lower_bound = [mean - std_dev for mean, std_dev in zip(means, std_devs)]
upper_bound = [mean + std_dev for mean, std_dev in zip(means, std_devs)]
# Plot mean line and get mean_line object
(mean_line,) = plt.plot(sizes, means, label=f"{name} (mean)")
# Get color of the mean line
color = mean_line.get_color()
# Plot lower and upper bounds as dashed lines of same color as mean line
plt.plot(
sizes,
lower_bound,
linestyle="--",
color=color,
label=f"{name} (mean - std_dev)",
)
plt.plot(
sizes,
upper_bound,
linestyle="--",
color=color,
label=f"{name} (mean + std_dev)",
)
# plot settings
plt.xlabel("Array Size")
plt.ylabel("Time [seconds]")
plt.title("Sorting Algorithm Performance")
plt.legend()
plt.grid(True)
plt.savefig("sorting_performance.png")
plt.show()