Skip to content

Instantly share code, notes, and snippets.

@ly29
Last active August 29, 2015 14:02
Show Gist options
  • Save ly29/e4d0a0e91a036aa5a0df to your computer and use it in GitHub Desktop.
Save ly29/e4d0a0e91a036aa5a0df to your computer and use it in GitHub Desktop.
flatten recurse a little bit
from timeit import Timer
setup = """
from mathutils import Vector
from random import random
ul = [[[random(),random(),random()] for i in range(1000)]]
v1 = [[[random(),random(),random()] for i in range(1000)]]
v2 = [[[0,0,1]]]
def fullList(l, count):
d = count - len(l)
if d > 0:
l.extend([l[-1] for a in range(d)])
return
cross = lambda u,v:u.cross(v)[:]
def recurse_fxy( l1, l2, f, leve):
if not leve:
return f(Vector(l1), Vector(l2))
else:
max_obj = max(len(l1), len(l2))
fullList(l1, max_obj)
fullList(l2, max_obj)
res = []
res_append = res.append
for i in range(len(l1)):
res_append(recurse_fxy(l1[i], l2[i], f, leve - 1))
return res
def recurse_fxy2(l1, l2, f, leve):
if leve==1:
max_obj = max(len(l1),len(l2))
res = []
res_append = res.append
for i,obj in enumerate(zip(l1,l2)):
res_append(f(Vector(obj[0]),Vector(obj[1])))
if i < max_obj-1:
if len(l1)-1==i:
v_l1=Vector(l1[-1])
for i in range(i,max_obj):
res_append(f(v_l1,Vector(l2[i])))
else:
v_l2=Vector(l2[-1])
for i in range(i,max_obj):
res_append(f(Vector(l1[i]),v_l2))
return res
elif leve > 1:
max_obj = max(len(l1),len(l2))
fullList(l1, max_obj)
fullList(l2, max_obj)
res = []
for i in range(len(l1)):
res.append(recurse_fxy2(l1[i], l2[i],f, leve-1))
return res
"""
def test(r=3,times=1000):
t1 = Timer("""w = recurse_fxy(ul,v1,cross,2)""", setup=setup)
print("fxy 1000:1000:", min(t1.repeat(r,times)))
t2 = Timer("""w = recurse_fxy2(ul,v1,cross,2)""", setup=setup)
print("fxy2 1000:1000:", min(t2.repeat(r,times)))
t3 = Timer("""w = recurse_fxy(ul,v2,cross,2)""", setup=setup)
print("fxy : 1000:1", min(t3.repeat(r,times)))
t4 = Timer("""w = recurse_fxy2(ul,v2,cross,2)""", setup=setup)
print("fxy2: 1000:1", min(t4.repeat(r,times)))
test()
@ly29
Copy link
Author

ly29 commented Jun 14, 2014

fxy 1000:1000: 1.0623891800059937
fxy2 1000:1000: 0.893612664018292
fxy : 1000:1 1.142882157000713
fxy2: 1000:1 0.6401150920137297

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment