[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to count the number of lines in a string?
- From: "Jerome Vuarand" <jerome.vuarand@...>
- Date: Thu, 31 Jul 2008 14:24:23 +0200
2008/7/31 Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br>:
>> local n = select(2, s:gsub('\n', '\n'))
>
> This one creates a new string (identical to the original one).
But there are fewer function calls, and it ends up being faster. Here
are some test results (13 generates data, 14 is with gsub, 15 with
gmatch), on Windows XP 32bits on a Intel Core 2 Quad Q6600 @ 2.4GHz
with a tool called ptime [1] :
> lua test13.lua 10 > test1415.dat
> ptime lua test14.lua 1000000
Execution time: 1.717 s
> ptime lua test15.lua 1000000
Execution time: 3.125 s
> lua test13.lua 1000 > test1415.dat
> ptime lua test14.lua 10000
Execution time: 1.383 s
> ptime lua test15.lua 10000
Execution time: 2.440 s
> lua test13.lua 100000 > test1415.dat
> ptime lua test14.lua 100
Execution time: 1.640 s
> ptime lua test15.lua 100
Execution time: 2.425 s
And the source code:
-- test13.lua
for i=1,tonumber((...)) do
print("foo")
end
-- test14.lua
local str = io.open("test1415.dat"):read"*a"
for i=1,tonumber((...)) do
local n = select(2, str:gsub('\n', '\n'))
end
-- test15.lua
local str = io.open("test1415.dat"):read"*a"
for i=1,tonumber((...)) do
local n=0
for i in str:gmatch("\n") do n=n+1 end
end
--
[1] http://www.pc-tools.net/win32/ptime/