Last active
December 23, 2022 12:15
-
-
Save stephengruppetta/6fd6c85144027c6cb4b5f597f7984f78 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import sys | |
import time | |
import numpy as np | |
numbers = [random.randint(-100, 450) / 10 for _ in range(10_000_000)] | |
numbers_np = np.array(numbers) | |
def convert_list(data): | |
output = [] | |
for value in data: | |
output.append(value * 1.8 + 32) | |
return output | |
def convert_list_comp(data): | |
return [value * 1.8 + 32 for value in data] | |
def convert_numpy(data: np.ndarray): | |
return data * 1.8 + 32 | |
print(f"Using Python version {sys.version}") | |
# Confirm all versions give the same result | |
print( | |
convert_list(numbers) | |
== convert_list_comp(numbers) | |
== list(convert_numpy(numbers_np)) | |
) | |
# Run all three functions and time them | |
start = time.time() | |
convert_list(numbers) | |
time_list = time.time() - start | |
start = time.time() | |
convert_list_comp(numbers) | |
time_comp = time.time() - start | |
start = time.time() | |
convert_numpy(numbers_np) | |
time_numpy = time.time() - start | |
# Show results | |
print(f"\nUsing list: {time_list:0.5f} s") | |
print(f"Using list comprehension: {time_comp:0.5f} s") | |
print(f"Using numpy: {time_numpy:0.5f} s") | |
print( | |
f"\nList comp is {time_list/time_comp:0.2f} times faster than lists" | |
) | |
print( | |
f"Numpy array is {time_list/time_numpy:0.2f} times faster than lists" | |
) | |
# OUTPUT: | |
# Using Python version 3.10.5 (v3.10.5:f377153967, Jun 6 2022, 12:36:10) [Clang 13.0.0 (clang-1300.0.29.30)] | |
# True | |
# | |
# Using list: 0.59864 s | |
# Using list comprehension: 0.36916 s | |
# Using numpy: 0.01285 s | |
# | |
# List comp is 1.62 times faster than lists | |
# Numpy array is 46.59 times faster than lists |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment