Created
December 23, 2022 12:16
-
-
Save stephengruppetta/24dc4cbe3124a172a176127a41c71860 to your computer and use it in GitHub Desktop.
This file contains 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.11.0 (v3.11.0:deaf509e8f, Oct 24 2022, 14:43:23) [Clang 13.0.0 (clang-1300.0.29.30)] | |
# True | |
# | |
# Using list: 0.36446 s | |
# Using list comprehension: 0.32340 s | |
# Using numpy: 0.01132 s | |
# | |
# List comp is 1.13 times faster than lists | |
# Numpy array is 32.19 times faster than lists |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment