Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- Locals vs Globals benchmark test
- @version 1.0, 2015-06-06
- @author TheOddByte, Erik Hougaard
- --]]
- function yield()
- os.queueEvent( "sleep" )
- coroutine.yield( "sleep" )
- end
- function sieve( n )
- x = {}
- iter = 0
- repeat
- x[1] = 0
- i = 2
- repeat
- x[i] = 1
- i = i + 1
- until i > n
- p = 2
- while(p * p <= n) do
- j = p
- while(j <= n) do
- x[j] = 0
- j = j + p
- end
- repeat
- p = p + 1
- until x[p] == 1
- end
- iter = iter + 1
- yield() --# Yield, just to make sure it isn't erroring
- until iter == 101
- end
- function sieve_locals( n )
- local x = {}
- local iter = 0
- repeat
- x[1] = 0
- local i = 2
- repeat
- x[i] = 1
- i = i + 1
- until i > n
- local p = 2
- while(p * p <= n) do
- local j = p
- while(j <= n) do
- x[j] = 0
- j = j + p
- end
- repeat
- p = p + 1
- until x[p] == 1
- end
- iter = iter + 1
- yield() --# Yield, just to make sure it isn't erroring
- until iter == 101
- end
- --# Store results in these tables
- local locals = {}
- local globals = {}
- --# Indicate that the test has started
- local w, h = term.getSize()
- term.clear()
- term.setCursorPos( 1, 1 )
- print("Sieve of Eratosthenes - Lua Benchmark test 1.0\n" .. string.rep( "-", w ))
- print( "Original author: Erik Hougaard" )
- print( "Modified by: TheOddByte" )
- print("\n[".. textutils.formatTime( os.time(), true ) .. "] Started test")
- --# Test the function with local variables
- for i = 1, 10 do
- local start = os.clock()
- sieve_locals( 10000 )
- local stop = os.clock()
- table.insert( locals, ( stop - start ) )
- end
- --# Test the function with global variables
- for i = 1, 10 do
- local start = os.clock()
- sieve( 10000 )
- local stop = os.clock()
- table.insert( globals, ( stop - start ) )
- end
- print("[".. textutils.formatTime( os.time(), true ) .. "] Finished test")
- --# Get the average time of both tests
- --# And print them to the screen
- local a, b = 0, 0
- for i = 1, #locals do
- a = a + locals[i]
- b = b + globals[i]
- end
- print("\nAverage time with locals: " .. ( a/#locals ) .. " s" )
- print("Average time with globals: " .. ( b/#globals ) .. " s" )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement