Lua Profiler Examples

lua-users home
wiki

[!] VersionNotice: The below code pertains to an older Lua version, Lua 4. It does not run as is under Lua 5.

tinsert and tremove example

Look at this code:

t={[0]=1}
n=1000

function ins()
    for i = 1, n do
        tinsert(t, i)
    end
end

function rem()
    for i = 1, n do
        tremove(t, 1)
    end
end

ins()
tremove(t, 0)
rem()

After running the profiler, you get the resulting graph:

(the call to tremove from main is just to show that the profiler can tell you in which call point the bottleneck happens)

The graph shows that tremove is a bottleneck because it is the only black box. What to do since tremove is already a very fast routine? Whatever we do, to make the program faster we must concentrate on the call to tremove made from rem. Reading the tremove specification, we realize that it shifts all elements greater than n one row back at each call, and this takes time.

Since we don't need any shifting, there is a faster code that does the same thing:

t={[0]=1}
n=1000

function ins()
    for i = 1, n do
        tinsert(t, i)
    end
end

function rem()
    for i = n, 1, -1 do
        tremove(t, n)
    end
end

ins()
tremove(t, 0)
rem()

And the graph shows that there is no other bottlenecks (because the colors are almost the same). In fact, the black boxes are now ins and rem, so they are the functions that take more time to execute.

The first step took almost 1 second to execute in my pentium 200 MMX, and the second almost 0.


RecentChanges · preferences
edit · history
Last edited January 11, 2007 4:27 am GMT (diff)