Last active
November 20, 2018 17:21
-
-
Save gngdb/3d4f5aa27ee5199b0d4b997ffe21a6b4 to your computer and use it in GitHub Desktop.
index_select and then reshaping is faster than just indexing?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
if __name__ == '__main__': | |
X = torch.randn(100) | |
out_shape = (100,100) | |
idxs = torch.randint(high=100, size=out_shape).long() | |
assert torch.abs(X[idxs] - X.index_select(0, idxs.view(-1)).view(*out_shape)).max() < 1e-3 | |
from timeit import timeit | |
setup = 'import torch; X = torch.randn(100); out_shape=(100,100); idxs = torch.randint(high=100, size=out_shape).long()' | |
print("X[idxs]: ", timeit("_ = X[idxs]", setup=setup, number=100)) | |
print("X.index_select and reshape: ", timeit("_ = X.index_select(0, idxs.view(-1)).view(*out_shape)", setup=setup, number=100)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: