Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Does the magnitude of math.random values affect performance?

Asked by
Tesouro 407 Moderation Voter
10 years ago

The math.random() function has 2 values that the chosen number is between, m and n (as the wiki says).

Example: I have a script that gets a random value for the transparency of some part, that can be between 0 and 1. I can make

math.random(0, 1) --  can return me 2 values (0 or 1)

or

math.random(0, 100) / 100 -- can return me 101 values (like 0.06 or 0.84)

Ignoring the division by 100, does the number of options to randomly choose affect a script performance? Will the computer have to calculate a hundred times more?

(it may sound insignificant, but if I do it in a constant loop, for example, can I feel the difference?)

1 answer

Log in to vote
3
Answered by
2eggnog 981 Moderation Voter
10 years ago

The difference is almost completely negligible. I went ahead and ran a test, and the average difference between math.random(0,1) and math.random(0,100) is 9.5 microseconds (0.0000095 seconds.) You really don't need to worry.

In case you're wondering, this is script I used to figure that out:

local huget = {}
local smallt = {}
local hugeav = 0
local smallav = 0

for i = 1, 100 do
local t = tick()
print(math.random(0, 100))
table.insert(huget,tick()-t)
wait()
end

for i = 1, 100 do
local t = tick()
print(math.random(0,1))
table.insert(smallt,tick()-t)
wait()
end


for i,v in ipairs(huget) do
hugeav = hugeav + v
end
hugeav = hugeav/#huget

for i,v in ipairs(smallt) do
smallav = smallav + v
end
smallav = smallav/#smallt

print("average math.random(0,100) time: " .. hugeav)
print("average math.random(0,1) time: " .. smallav)
0
Hum... 0.0000095 seconds? That is much less that a rendering frame, so I think it won't be a problem heheh. Thanks for the answer. Tesouro 407 — 10y
0
Also, I made a test using 100000 instead of 100 (yeah, it took a lot of time) and the difference was only 0.0002, so I'm convinced. Tesouro 407 — 10y
Ad

Answer this question