-
-
Save stephengruppetta/c64373075c013f8647df78bcd10562c4 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 timeit | |
import numpy as np | |
# Create a list of temperatures | |
temperatures = [ | |
random.randint(-100, 350) / 10 | |
for _ in range(1_000_000) | |
] | |
# And create a NumPy 'ndarray' from that list | |
temperatures_np = np.array(temperatures) | |
# Functions to convert from ºC to ºF | |
def convert_using_loop(data): | |
result = [] | |
for temperature in data: | |
result.append(temperature * 1.8 + 32) | |
return result | |
def convert_using_numpy(data: np.ndarray): | |
return data * 1.8 + 32 | |
print('\nUsing the "classic" for loop method with a list:') | |
print( | |
timeit.timeit( | |
"convert_using_loop(temperatures)", | |
number=100, | |
globals=globals()), | |
) | |
print("\nUsing NumPy:") | |
print( | |
timeit.timeit( | |
"convert_using_numpy(temperatures_np)", | |
number=100, | |
globals=globals(), | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment