Skip to content

Instantly share code, notes, and snippets.

@albertbuchard
Last active July 23, 2022 21:39
Show Gist options
  • Save albertbuchard/e2936a422593919a13b66a642b3950e6 to your computer and use it in GitHub Desktop.
Save albertbuchard/e2936a422593919a13b66a642b3950e6 to your computer and use it in GitHub Desktop.
Comparison tensor fill
setup='''
import numpy as np
import torch
V_nat = [[1, 2], [3, 4]]
U_nat = [[2, -1, 0, 0, 0, 0],
[5, 2, 8, -1, 0, 0]]
def compute_using_fleuret_1():
U = torch.tensor(U_nat)
V = torch.tensor(V_nat)
for i in range(U.size(0)):
j = (U[i] == -1).nonzero()[0][0]
U[i, j:j + V.size(1)] = V[i]
def compute_using_fleuret_2():
U = torch.tensor(U_nat)
V = torch.tensor(V_nat)
indices = (U == -1).nonzero()
rows_done = set()
for i, row in enumerate(indices[0]):
if row in rows_done:
continue
rows_done.add(row)
col = indices[1][i]
U[row, col:col + V.size(1)] = V[row]
def compute_using_torch():
U = torch.tensor(U_nat)
V = torch.tensor(V_nat)
for i in range(U.size(0)):
for j in range(U.size(1)):
if U[i, j] == -1:
U[i, j:j + V.size(1)] = V[i]
break
def compute_using_numpy():
U = np.asarray(U_nat)
V = np.asarray(V_nat)
for i in range(U.shape[0]):
for j in range(U.shape[1]):
if U[i, j] == -1:
U[i, j:j + V.shape[1]] = V[i]
break
U = torch.tensor(U)
V = torch.tensor(V)
def compute_natively():
U = U_nat
V = V_nat
for i in range(len(U)):
for j in range(len(U[i])):
if U[i][j] == -1:
U[i][j:j + len(V[i])] = V[i]
break
U = torch.tensor(U)
V = torch.tensor(V)
'''
if __name__ == "__main__":
import timeit
print("Using fleuret method:")
print(timeit.timeit("compute_using_fleuret_1()", setup=setup, number=100))
print("Using fleuret method 2:")
print(timeit.timeit("compute_using_fleuret_2()", setup=setup, number=100))
print("Using torch without boolean mask:")
print(timeit.timeit("compute_using_torch()", setup=setup, number=100))
print("Using numpy:")
print(timeit.timeit("compute_using_numpy()", setup=setup, number=100))
print("Using native python:")
print(timeit.timeit("compute_natively()", setup=setup, number=100))
# Output:
# Using fleuret method:
# 0.002619250000000073
# Using fleuret method 2:
# 0.0024312090000000453
# Using torch without boolean mask:
# 0.00287004099999999
# Using numpy:
# 0.0008266660000000314
# Using native python:
# 0.0004074589999999434
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment