Created
August 31, 2016 09:11
-
-
Save iamalbert/40c2ba9cdbed69620feb5d597f499d47 to your computer and use it in GitHub Desktop.
lua coroutine vs plain loop
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
require 'sys' | |
local n = 100000 | |
local seq = {} | |
for i = 1, n do seq[i] = i end | |
local bs = 405 | |
local plainLoop = function() | |
local yield = {} | |
for i = 1, #seq do | |
table.insert( yield, seq[i] ) | |
if #yield == bs then | |
print(#yield) | |
yield = {} | |
end | |
end | |
if #yield > 0 then | |
print(#yield) | |
end | |
end | |
local coroutineYield = function() | |
local yield = {} | |
for i = 1, #seq do | |
table.insert( yield, seq[i] ) | |
if #yield == bs then | |
coroutine.yield(yield) | |
yield = {} | |
end | |
end | |
if #yield > 0 then | |
coroutine.yield(yield) | |
end | |
end | |
local coroutineLoop = function() | |
local iter = coroutine.wrap( coroutineYield ) | |
for r in iter do | |
print(#r) | |
end | |
end | |
sys.tic() | |
plainLoop() | |
local t1 = sys.toc() | |
sys.tic() | |
coroutineLoop() | |
local t2 = sys.toc() | |
print( "plain loop", t1 ) | |
print( "coroutine", t2 ) | |
--[[ | |
plain loop 0.0047900676727295 | |
coroutine 0.0039558410644531 | |
--]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment