Skip to content

Instantly share code, notes, and snippets.

@olidroide
Last active October 7, 2022 11:49
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 olidroide/8b161bfeafe2fb9ab5547a0f76259b19 to your computer and use it in GitHub Desktop.
Save olidroide/8b161bfeafe2fb9ab5547a0f76259b19 to your computer and use it in GitHub Desktop.
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])
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