Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

Optimization: Calculate Roots Speed (plus handy root function!)
Started by Caleb P Nov 04 2013 12:15 PM

- - - - -
No replies to this topic
sqrt math speed root
[TOPIC CONTROLS]
This topic has been archived. This means that you cannot reply to this topic.
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

Caleb P

[GLOBAL: userInfoPane.html]
Caleb P
  • Corona Geek

  • 1,424 posts
  • Corona SDK

Just a quick heads-up for anyone who reads this - to calculate a square root (or any other root, for that matter), use Lua math equations, not math.sqrt.

 

According to the test I made, using the equivalent x ^ 0.5 is approximately four times faster than localized math.sqrt. I knocked up a simple test for it, and here's my result:

 

Using localized math.sqrt:


Test Finished: 
    50000000 calculations
    3.718415 secs taken
    74.3672 ms on average
 
Test Finished: 
    50000000 calculations
    3.713201 secs taken
    74.26284 ms on average
 
Test Finished: 
    50000000 calculations
    3.723258 secs taken
    74.46406 ms on average

 

Using 100 ^ 0.5:

Test Finished: 
    50000000 calculations
    0.971279 secs taken
    19.42424 ms on average
 
Test Finished: 
    50000000 calculations
    0.973754 secs taken
    19.47412 ms on average
 
Test Finished: 
    50000000 calculations
    0.940703 secs taken
    18.81362 ms on average

 

Here's my test (comment/uncomment the lines to use different methods):

local print = print
local math_sqrt = math.sqrt
local system_getTimer = system.getTimer
 
local function test(iterations)
    local time = 0
    local totalTime = 0
    local testStart = system_getTimer()
 
    for i = 1, iterations do
        local startTime = system_getTimer()
 
        for i = 1, 1000000 do
            --local t = 100 ^ 0.5
            local t = math_sqrt(100)
        end
 
        local testTime = system_getTimer() - startTime
        time = time + testTime
    end
 
    time = time / iterations -- Average the result
    totalTime = system_getTimer() - testStart
 
    local result = "\n\nTest Finished: \n\t" .. iterations * 1000000 .. " calculations\n\t" .. totalTime / 1000 .. " secs taken\n\t" .. time .. " ms on average"
    print(result)
end
 
for i = 1, 3 do
    test(50)
end
 
There's the root speed part of the title. Now, for the "handy root function" part - you can calculate the nth root of any number with this quick function:
local function nroot(n, r) return n ^ (1 / r) end
 
local result1 = nroot(50, 3) -- The cube root of 50
local result2 = nroot(128.5, 9) -- The ninth root of 128.5
 
 
Anyhow... Just testing out some root calculations :)
 
- Caleb



[topic_controls]
 
[/topic_controls]