Skip to content

Instantly share code, notes, and snippets.

@airalcorn2
Created June 3, 2025 11:52
Show Gist options
  • Save airalcorn2/23380b267ce422e6c3f24241b0a33c46 to your computer and use it in GitHub Desktop.
Save airalcorn2/23380b267ce422e6c3f24241b0a33c46 to your computer and use it in GitHub Desktop.
import numpy as np
import time
l = [np.random.randint(1000) for i in range(1000000)]
for use_arr in [False, True]:
if use_arr:
print("Using NumPy array.\n")
l = np.array(l)
else:
print("Using Python list.\n")
l_arr = np.array(l)
len_l = len(l)
samps = 20
choice_times = []
choice_length_times = []
int_times = []
for samp in range(samps):
start_time = time.perf_counter()
np.random.choice(l)
choice_times.append(time.perf_counter() - start_time)
start_time = time.perf_counter()
l[np.random.choice(len_l)]
choice_length_times.append(time.perf_counter() - start_time)
start_time = time.perf_counter()
l[np.random.randint(len_l)]
int_times.append(time.perf_counter() - start_time)
med_choice_time = np.median(choice_times)
med_choice_length_time = np.median(choice_length_times)
med_int_time = np.median(int_times)
print(f"Choice: {med_choice_time}")
print(f"Choice (Length): {med_choice_length_time}")
print(f"Int: {med_int_time}\n")
print(f"Choice / Choice (Length): {med_choice_time / med_choice_length_time}")
print(f"Choice / Int: {med_choice_time / med_int_time}\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment