Skip to content

Instantly share code, notes, and snippets.

@andreaskoepf
Created December 12, 2015 20:46
Show Gist options
  • Save andreaskoepf/8c646142e5414427e282 to your computer and use it in GitHub Desktop.
Save andreaskoepf/8c646142e5414427e282 to your computer and use it in GitHub Desktop.
Performance comparison between tensor type string lookup and metatable-function selector...
x = torch.DoubleTensor()
y = torch.FloatTensor()
function testfunc(a,b)
return a + b
end
f = {}
f[x:type()] = {}
f[y:type()] = {}
f[x:type()].funcA = testfunc;
f[y:type()].funcA = testfunc;
m1 = getmetatable(x)
m2 = getmetatable(y)
m1.xx = {}
m2.xx = {}
m1.xx.funcA = testfunc;
m2.xx.funcA = testfunc;
function benchmark_typelookup(n,t,fn)
for i=1,n do
f[t:type()][fn](i,i)
end
end
function benchmark_metatable(n,t,fn)
for i=1,n do
t.xx[fn](i,i)
end
end
t = torch.tic()
benchmark_typelookup(5000000, x, 'funcA')
benchmark_typelookup(5000000, y, 'funcA')
timeA = torch.toc(t)
t = torch.tic()
benchmark_metatable(5000000, x, 'funcA')
benchmark_metatable(5000000, y, 'funcA')
timeB = torch.toc(t)
print('typelookup: ' ..timeA)
print('metatable: '..timeB)
--[[
on my machine:
typelookup: 2.3007190227509
metatable: 1.5103120803833
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment