Skip to content

Instantly share code, notes, and snippets.

@stephengruppetta
Created January 6, 2024 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephengruppetta/c64373075c013f8647df78bcd10562c4 to your computer and use it in GitHub Desktop.
Save stephengruppetta/c64373075c013f8647df78bcd10562c4 to your computer and use it in GitHub Desktop.
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