-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
308 lines (256 loc) · 11.1 KB
/
main.py
File metadata and controls
308 lines (256 loc) · 11.1 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
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import math
import sys
import matplotlib.pyplot as plt
import memory_profiler
import numpy as np
import pandas as pd
import random
import seaborn as sns
from time import perf_counter
# Constants
COUNT = 1_000_000
NUM_RUNS = 10
RANDOM_SEED = 42
random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
# Time generation
def compare_generation_times() -> tuple[float, float]:
complex_gen_times = []
vector_gen_times = []
for _ in range(NUM_RUNS):
start = perf_counter()
complex_numbers = [
complex(random.uniform(-1, 1), random.uniform(-1, 1)) for _ in range(COUNT)
]
end = perf_counter()
complex_gen_times.append(end - start)
start = perf_counter()
vectors = np.random.uniform(-1, 1, (COUNT, 2))
end = perf_counter()
vector_gen_times.append(end - start)
return (sum(complex_gen_times) / NUM_RUNS, sum(vector_gen_times) / NUM_RUNS)
def compare_access_times() -> tuple[float, float]:
complex_access_times = []
vector_access_times = []
for _ in range(NUM_RUNS):
complex_numbers = [
complex(random.uniform(-1, 1), random.uniform(-1, 1)) for _ in range(COUNT)
]
vectors = np.random.uniform(-1, 1, (COUNT, 2))
start = perf_counter()
for z in complex_numbers:
real = z.real
imag = z.imag
end = perf_counter()
complex_access_times.append(end - start)
start = perf_counter()
for v in vectors:
x = v[0]
y = v[1]
end = perf_counter()
vector_access_times.append(end - start)
return (sum(complex_access_times) / NUM_RUNS, sum(vector_access_times) / NUM_RUNS)
def compare_memory_usage() -> tuple[float, float]:
# Generate 1 million complex numbers as a numpy array
complex_array = np.array([complex(random.uniform(-1, 1), random.uniform(-1, 1)) for _ in range(1_000_000)])
complex_size = complex_array.nbytes / (1024 ** 2) # Convert bytes to megabytes
# Generate 1 million 2D vectors as a numpy array
vector_array = np.random.uniform(-1, 1, (1_000_000, 2))
vector_size = vector_array.nbytes / (1024 ** 2) # Convert bytes to megabytes
return (complex_size, vector_size)
def compare_addition_times() -> tuple[float, float]:
complex_addition_times = []
vector_addition_times = []
for _ in range(NUM_RUNS):
c1, c2 = complex(random.uniform(-1, 1), random.uniform(-1, 1)), complex(
random.uniform(-1, 1), random.uniform(-1, 1)
)
start = perf_counter()
for _ in range(COUNT):
z = c1 + c2
end = perf_counter()
complex_addition_times.append(end - start)
v1 = np.random.uniform(-1, 1, 2)
v2 = np.random.uniform(-1, 1, 2)
start = perf_counter()
for _ in range(COUNT):
v = v1 + v2
end = perf_counter()
vector_addition_times.append(end - start)
return (sum(complex_addition_times) / NUM_RUNS, sum(vector_addition_times) / NUM_RUNS)
def compare_dp_times() -> tuple[float, float]:
complex_dot_times = []
vector_dot_times = []
for _ in range(NUM_RUNS):
c1, c2 = complex(random.uniform(-1, 1), random.uniform(-1, 1)), complex(
random.uniform(-1, 1), random.uniform(-1, 1)
)
start = perf_counter()
for _ in range(COUNT):
z = c1.real * c2.real + c1.imag * c2.imag
end = perf_counter()
complex_dot_times.append(end - start)
v1 = np.random.uniform(-1, 1, 2)
v2 = np.random.uniform(-1, 1, 2)
start = perf_counter()
for _ in range(COUNT):
v = v1[0] * v2[0] + v1[1] * v2[1]
end = perf_counter()
vector_dot_times.append(end - start)
return (sum(complex_dot_times) / NUM_RUNS, sum(vector_dot_times) / NUM_RUNS)
def compare_magnitude_times() -> tuple[float, float]:
complex_magnitude_times = []
vector_magnitude_times = []
for _ in range(NUM_RUNS):
c = complex(random.uniform(-1, 1), random.uniform(-1, 1))
start = perf_counter()
for _ in range(COUNT):
z = abs(c)
end = perf_counter()
complex_magnitude_times.append(end - start)
v = np.random.uniform(-1, 1, 2)
start = perf_counter()
for _ in range(COUNT):
z = np.linalg.norm(v)
end = perf_counter()
vector_magnitude_times.append(end - start)
return (sum(complex_magnitude_times) / NUM_RUNS, sum(vector_magnitude_times) / NUM_RUNS)
def get_rotation_times() -> tuple[float, float]:
complex_rotation_times = []
vector_rotation_times = []
for _ in range(NUM_RUNS):
angle = random.uniform(0, 2 * np.pi)
rotation_complex = complex(np.cos(angle), np.sin(angle))
rotation_matrix = np.array(
[[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]
)
c = complex(random.uniform(-1, 1), random.uniform(-1, 1))
start = perf_counter()
for _ in range(COUNT):
z = c * rotation_complex
end = perf_counter()
complex_rotation_times.append(end - start)
v = np.random.uniform(-1, 1, 2)
start = perf_counter()
for _ in range(COUNT):
v = rotation_matrix @ v
end = perf_counter()
vector_rotation_times.append(end - start)
return (sum(complex_rotation_times) / NUM_RUNS, sum(vector_rotation_times) / NUM_RUNS)
def main():
# Generation
print("== Generating ==")
complex_gen_time, vector_gen_time = compare_generation_times()
print(f"Time to generate complex numbers: {complex_gen_time:.4f} seconds")
print(f"Time to generate vectors: {vector_gen_time:.4f} seconds")
ratio = max(complex_gen_time, vector_gen_time) / min(complex_gen_time, vector_gen_time)
print(f"{'Complex numbers' if complex_gen_time < vector_gen_time else 'Vectors'} are {ratio:.2f}x faster to generate")
# Access
print("\n== Accessing ==")
complex_access_time, vector_access_time = compare_access_times()
print(f"Time to access complex numbers: {complex_access_time:.4f} seconds")
print(f"Time to access vectors: {vector_access_time:.4f} seconds")
ratio = max(complex_access_time, vector_access_time) / min(complex_access_time, vector_access_time)
print(f"{'Complex numbers' if complex_access_time < vector_access_time else 'Vectors'} are {ratio:.2f}x faster to access")
# Memory
print("\n== Memory Usage ==")
complex_size, vector_size = compare_memory_usage()
print(f"Memory usage for complex numbers: {complex_size:.1f} MB")
print(f"Memory usage for vectors: {vector_size:.1f} MB")
ratio = max(complex_size, vector_size) / min(complex_size, vector_size)
print(f"{'Complex numbers' if complex_size < vector_size else 'Vectors'} are {ratio:.2f}x more memory efficient")
# Addition
print("\n== Addition ==")
complex_addition_time, vector_addition_time = compare_addition_times()
print(f"Time to add complex numbers: {complex_addition_time:.4f} seconds")
print(f"Time to add vectors: {vector_addition_time:.4f} seconds")
ratio = max(complex_addition_time, vector_addition_time) / min(complex_addition_time, vector_addition_time)
print(f"{'Complex numbers' if complex_addition_time < vector_addition_time else 'Vectors'} are {ratio:.2f}x faster to add")
# Dot Product
print("\n== Dot Product ==")
complex_dot_time, vector_dot_time = compare_dp_times()
print(f"Time to dot product complex numbers: {complex_dot_time:.4f} seconds")
print(f"Time to dot product vectors: {vector_dot_time:.4f} seconds")
ratio = max(complex_dot_time, vector_dot_time) / min(complex_dot_time, vector_dot_time)
print(f"{'Complex numbers' if complex_dot_time < vector_dot_time else 'Vectors'} are {ratio:.2f}x faster to dot product")
# Magnitude
print("\n== Magnitude ==")
complex_magnitude_time, vector_magnitude_time = compare_magnitude_times()
print(f"Time to magnitude complex numbers: {complex_magnitude_time:.4f} seconds")
print(f"Time to magnitude vectors: {vector_magnitude_time:.4f} seconds")
ratio = max(complex_magnitude_time, vector_magnitude_time) / min(complex_magnitude_time, vector_magnitude_time)
print(f"{'Complex numbers' if complex_magnitude_time < vector_magnitude_time else 'Vectors'} are {ratio:.2f}x faster to magnitude")
# Rotation
print("\n== Rotation ==")
complex_rotation_time, vector_rotation_time = get_rotation_times()
print(f"Time to rotate complex numbers: {complex_rotation_time:.4f} seconds")
print(f"Time to rotate vectors: {vector_rotation_time:.4f} seconds")
ratio = max(complex_rotation_time, vector_rotation_time) / min(complex_rotation_time, vector_rotation_time)
print(f"{'Complex numbers' if complex_rotation_time < vector_rotation_time else 'Vectors'} are {ratio:.2f}x faster to rotate")
# Create visualization
metrics = ["Generation", "Access", "Addition", "Dot Product", "Magnitude", "Rotation"]
complex_times = [
complex_gen_time,
complex_access_time,
complex_addition_time,
complex_dot_time,
complex_magnitude_time,
complex_rotation_time,
]
vector_times = [
vector_gen_time,
vector_access_time,
vector_addition_time,
vector_dot_time,
vector_magnitude_time,
vector_rotation_time,
]
df = pd.DataFrame(
{
"Category": metrics * 2,
"Time (seconds)": complex_times + vector_times,
"Type": ["Complex Numbers"] * len(metrics) + ["Vectors"] * len(metrics),
}
)
# Create the grouped bar graph excluding memory usage
plt.figure(figsize=(12, 6))
sns.barplot(
data=df, x="Category", y="Time (seconds)", hue="Type", palette="Set2"
)
plt.title(
"Performance Comparison: Complex Numbers vs Vectors (Excluding Memory Usage)",
fontsize=16,
)
plt.ylabel("Time (seconds)", fontsize=12)
plt.xlabel("Category", fontsize=12)
plt.xticks(rotation=45, ha="right")
plt.legend(title="Data Type", fontsize=10)
plt.tight_layout()
# Create memory profile visualization
memory_metrics = ["Memory Usage"]
memory_df = pd.DataFrame({
"Category": memory_metrics * 2,
"Memory (MB)": [complex_size, vector_size],
"Type": ["Complex Numbers", "Vectors"]
})
plt.figure(figsize=(8, 6))
sns.barplot(
data=memory_df, x="Category", y="Memory (MB)", hue="Type", palette="Set2"
)
plt.title("Memory Usage: Complex Numbers vs Vectors", fontsize=16)
plt.ylabel("Memory (MB)", fontsize=12)
plt.xlabel("Category", fontsize=12)
plt.legend(title="Data Type", fontsize=10)
plt.tight_layout()
# Show the plot
plt.show()
if __name__ == "__main__":
main()
complex_memory, vector_memory = compare_memory_usage()
print(complex_memory, vector_memory)
# Compare memory usage of a single complex number vs a single vector
single_complex = complex(1.0, 1.0)
single_vector = np.array([1.0, 1.0])
print("\nSingle element memory usage:")
print(f"Complex number: {sys.getsizeof(single_complex)} bytes")
print(f"NumPy vector: {single_vector.nbytes} bytes")