Skip to content

Instantly share code, notes, and snippets.

@apaszke
Created March 11, 2020 12:04
Show Gist options
  • Save apaszke/fef347c22472c12f0cfb9da17e8241eb to your computer and use it in GitHub Desktop.
Save apaszke/fef347c22472c12f0cfb9da17e8241eb to your computer and use it in GitHub Desktop.
import time
import numpy as np
segments = np.ones((100000, 12, 3))
M = np.ones((4, 4))
def _proj_transform_vectors(vecs, M):
is_masked = isinstance(vecs, np.ma.MaskedArray)
if is_masked:
mask = vecs.mask
vecs_pad = np.empty((vecs.shape[0] + 1,) + vecs.shape[1:])
vecs_pad[:-1] = vecs
vecs_pad[-1] = 1
product = np.dot(M, vecs_pad)
result = product[:3] / product[3]
if is_masked:
return np.ma.array(result, mask=mask)
else:
return result
def baseline():
num_faces, num_face_vertices, _ = segments.shape
vecs = segments.reshape(-1, 3).T
_, _, pzs = pvecs = _proj_transform_vectors(vecs, M)
del vecs # To avoid typos with pvecs
psegments = pvecs.T.reshape(segments.shape)
assert psegments.shape == (num_faces, num_face_vertices, 3)
epilogue(psegments)
def _proj_transform_vectors_new(vecs, M):
is_masked = isinstance(vecs, np.ma.MaskedArray)
if is_masked:
mask = vecs.mask
vecs_pad = np.empty(vecs.shape[:-1] + (vecs.shape[-1] + 1,))
vecs_pad[..., :-1] = vecs
vecs_pad[..., -1] = 1
product = vecs_pad @ M.T
result = product[..., :3] / product[..., 3:]
if is_masked:
return np.ma.array(result, mask=mask)
else:
return result
def new():
psegments = _proj_transform_vectors_new(segments, M)
epilogue(psegments)
def epilogue(psegments):
face_z = np.mean(psegments[..., 2], axis=-1)
if isinstance(face_z, np.ma.MaskedArray):
# NOTE: Unpacking .data is safe here, because every face has to contain
# a valid vertex.
face_z = face_z.data
face_order = np.argsort(face_z, axis=-1)[::-1]
np.min(psegments[..., 2])
from timeit import timeit
N = 25
new_t = timeit(new, number=N) / N * 1000
baseline_t = timeit(baseline, number=N) / N * 1000
print('New:\t\t{: .2f}ms'.format(new_t))
print('Baseline:\t{: .2f}ms'.format(baseline_t))
print('Diff:\t\t{: .2f}ms'.format(baseline_t - new_t))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment