lua-users home
lua-l archive

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


 >> >> accessing locals is faster than globals.

lhf wrote:
 >> This is true. But I don't know how much faster.

  Following is the test I ran, you may be able to spot flaws in it.  On a
Pentium III 500 under Win98 I got the following results with the "official"
Lua 3.2 executable, indicating about a 2::1 performance gain from locals:

overhead = 49
locals   = 10
globals  = 23

  (Of course, it takes a hundred million cycles to identify a whopping 13
seconds, so what's the big deal, right?  <grin>  Also, as has been
mentioned in this list before, the overhead of the test dwarfs the actual
difference of the code being tested.)


---cut here---

-- timer.lua - compare local vs global variable access

-- the real clock() seems to be unreliable in Windows
function clock()
  return tonumber(date("%M"))*60+tonumber(date("%S"))
end

-- have to loop many times to overcome clock() resolution
limit=100000000

function TimeLoop()
  local i=limit
  local start=clock()
  while i > 0 do
    i=i-1
  end
  return clock()-start
end

function TimeLocals()
  local la,lb=1.2345
  local i=limit
  local start=clock()
  while i > 0 do
    lb = la
    i=i-1
  end
  return clock()-start
end

ga,gb=1.2345
function TimeGlobals()
  local i=limit
  local start=clock()
  while i > 0 do
    gb = ga
    i=i-1
  end
  return clock()-start
end

overhead=TimeLoop()
print("overhead = "..overhead)
print("locals   = "..TimeLocals()-overhead)
print("globals  = "..TimeGlobals()-overhead)