Hello. I’m making tree generation system. I did 2 tree grow patterns already, and now I’m making third - for trees like pine. For it I need use function, which will generate -1 or 1 randomly. But what’s the fastest way to achieve it?
I found this way:
(math.random(0, 1) - 0.5) * 2
(10.000.000 usings cost 0.5 s)
Also, before I used
if math.random(0, 1) == 0 then -1 else 1
but this way, 10.000.000 usings cost 0.7 s
So, I start wondering:
Is there any faster ways to get that value?
I can’t think of any faster way, even micro optimizations like this are usually not worth it though. A difference of 0.2 ms is pretty okay, but you can probably improve other areas of the code more.
Side note:Timed performance tests are not ideal for comparing different instructions, as it may vary on multiple factors. While it may be quite consistent on one machine, it may still vary. For me I got values between as high as 0.75 from time to time on your most efficient test, while mostly landing in the 0.34 range.
It may be hard to tell exactly how many instructions are being executed by the CPU, but just looking at the code it seems to be one of the simplest possible operations. Randomizing may take some time, but the rest of it (the arithmetic portion) is quick. Either way, improving by an additional millisecond or two probably won’t make or break your game. Instead, as I mentioned before, I recommend you focus your attention elsewhere. Is there a particular reason you want an even faster way than this?
local s = os.clock()
local num = 1664525 * s + 1013904223
for i = 1, 1e6 do
if num == 0 then
num = 1664525 * num + 1013904223
end
local THERANDOMNUMBER = (bit32.band(num, 1) - 0.5) * 2
num = bit32.rshift(num, 1)
end
print(os.clock() - s)
local s = os.clock()
for i = 1, 1e6 do
local THERANDOMNUMBER = (math.random(0, 1) - 0.5) * 2
end
print(os.clock() - s)