Skip to content

Instantly share code, notes, and snippets.

@jul
Last active July 6, 2019 22:20
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 jul/a4dbf1e691a1ac6601aa7498fdf0b3e6 to your computer and use it in GitHub Desktop.
Save jul/a4dbf1e691a1ac6601aa7498fdf0b3e6 to your computer and use it in GitHub Desktop.
perf diff between reduce vs sum
from functools import reduce as r
from time import time as t
add = str.__add__
class S(str):
__neutral = ""
def __radd__(s, o):
o = o or S.__neutral
return add(s, o)
def __ladd__(o, s):
o = o or S.__neutral
return add(s, o)
def __add__(s, o):
o = o or S.__neutral
return add(o, s)
y = list(map(S,range(900900)))
print("reduce")
i = t()
z=r(S.__add__, y)
print(t() - i)
print("reduce2")
i = t()
w=r(S.__ladd__, y)
print(t() - i)
print("sum")
i = t()
y=sum(y)
print(t() - i)
assert y==z,"%s != %s" % (y,z)
assert w==z,"%s != %s" % (w,z)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment