Skip to content

Instantly share code, notes, and snippets.

@nefftd
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save nefftd/91194f8e275c6a737aa5 to your computer and use it in GitHub Desktop.

Select an option

Save nefftd/91194f8e275c6a737aa5 to your computer and use it in GitHub Desktop.
-- Implementations
local function randstring_1(size)
local c,r = string.char,math.random
local str = {}
for i = 1,size do
str[i] = c(r(0,255))
end
return table.concat(str)
end
local MAX_UNPACK_SIZE = 50000
local function randstring_2(size)
local c,r,u,m = string.char,math.random,(table.unpack or unpack),math.min
local str,temp,n = {},{},1
while size > 0 do
local L = m(size,MAX_UNPACK_SIZE)
for i = 1,L do
temp[i] = r(0,255)
end
str[n] = c(u(temp,1,L))
n = n + 1
size = size - L
end
return table.concat(str)
end
-- Profile
local tests = {10^3, 10^4, 10^5, 10^6, 10^7, 10^8, 10^9}
for i,size in ipairs(tests) do
collectgarbage('collect')
collectgarbage('collect')
local t = os.clock()
randstring_1(size)
print('method 1 ('..size..'):',(os.clock() - t))
collectgarbage('collect')
collectgarbage('collect')
local t = os.clock()
randstring_2(size)
print('method 2 ('..size..'):',(os.clock() - t))
end
--[[ RESULTS on i5-2520M w/ 6 GiB 1333 MHz RAM on Windows 7 SP1 64-bit, via
64-bit Lua 5.2.3 from http://joedf.users.sourceforge.net/luabuilds/:
D:\Desktop
λ lua test.lua
method 1 (1000): 0
method 2 (1000): 0
method 1 (10000): 0.002
method 2 (10000): 0.002
method 1 (100000): 0.026
method 2 (100000): 0.014
method 1 (1000000): 0.269
method 2 (1000000): 0.134
method 1 (10000000): 2.828
method 2 (10000000): 1.317
method 1 (100000000): 27.333
method 2 (100000000): 13.064
lua: not enough memory
NOTES: On the second-to-last test (10^8), method 1 climbed to ~2.5 GiB of memory
to generate the random string, while method 2 used less than 150 MiB. Method 2's
speed (and memory consumption) can be improved furhter by using larger values
for MAX_UNPACK_SIZE. You need to see what is acceptable. It varies by platform
and build of Lua, it seems.
--]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment