Last active
October 7, 2022 11:49
-
-
Save olidroide/8b161bfeafe2fb9ab5547a0f76259b19 to your computer and use it in GitHub Desktop.
Check for loop Python performance based in this thread https://stackoverflow.com/questions/22108488/are-list-comprehensions-and-functional-functions-faster-than-for-loops
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
from functools import reduce | |
import datetime | |
def time_it(func, numbers, *args): | |
start_t = datetime.datetime.now() | |
for i in range(numbers): | |
func(args[0]) | |
print (datetime.datetime.now()-start_t) | |
def square_sum1(numbers): | |
return reduce(lambda sum, next: sum+next**2, numbers, 0) | |
def square_sum2(numbers): | |
a = 0 | |
for i in numbers: | |
a += i**2 | |
return a | |
def square_sum3(numbers): | |
a = 0 | |
map(lambda x: a+x**2, numbers) | |
return a | |
def square_sum4(numbers): | |
a = 0 | |
return [a+i**2 for i in numbers] | |
print("reduce") | |
time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3]) | |
print("for loop") | |
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3]) | |
print("map") | |
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3]) | |
print("list comprehension") | |
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3]) |
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
reduce | |
0:00:00.223160 | |
for loop | |
0:00:00.187482 | |
map | |
0:00:00.022508 | |
list comprehension | |
0:00:00.208897 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment