lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Jan 14, 2010, at 6:44 PM, Alexander Gladysh wrote:

> On Fri, Jan 15, 2010 at 04:49, Mark Hamburg <mark@grubmah.com> wrote:
>> On Jan 14, 2010, at 7:15 AM, Mark Hamburg wrote:
> 
>>> While upvalues are slower than locals, I suspect that a table lookup is slower still.
> 
>> Some statistics. This basically is the result of timing a loop that counts up to a really big number using various ways of storing the counter.
> 
> <...>
> 
> When posting benchmarks, please consider publishing benchmarked code
> so other could reproduce results.

Okay. It's a little long.

----

local jit = jit

if jit == nil then
	jit = {
		on = function() end,
		off = function() end,
		flush = function() end
	}
end

local function time_it( k, ... )

	if type( k ) ~= 'number' then
		return time_it( 1, k, ... )
	end
	
	jit.flush()

	local clock = os.clock
	
	local start = clock()
	
	for i = 1, k do
		pcall( ... )
	end
	
	local finish = clock()
	
	return finish - start

end

local tests = { }

local function countLocal( limit )
	local x = 0
	while x < limit do
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
	end
end

tests[ "Local" ] = countLocal

local function makeCountUpvalue()
	local x = 0
	return function( limit )
		while x < limit do
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
		end
	end
end

local function countUpvalue( limit )
	makeCountUpvalue()( limit )
end

tests[ "Upvalue" ] = countUpvalue

local function countUpvalueOnStack( limit )
	local x = 0
	local f = function( limit )
		while x < limit do
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
			x = x + 1
		end
	end
	f( limit )
end

tests[ "Upvalue on stack" ] = countUpvalueOnStack

local function countTable( limit )
	local t = { x = 0 }
	while t.x < limit do
		t.x = t.x + 1
		t.x = t.x + 1
		t.x = t.x + 1
		t.x = t.x + 1
		t.x = t.x + 1
		t.x = t.x + 1
		t.x = t.x + 1
		t.x = t.x + 1
		t.x = t.x + 1
		t.x = t.x + 1
	end
end

tests[ "Table" ] = countTable

local function countGlobal( limit )
	x = 0
	while x < limit do
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
		x = x + 1
	end
end

tests[ "Global" ] = countGlobal

local limit = 10 * 1000 * 1000 * 1000

for k, v in pairs( tests ) do
	print( k, time_it( v, limit ) )
end