Last time, we did a comparison of multiplication and division — and multiplication clearly won. Not by incredible amounts but enough that it was clearly the winner. That test really only applied to interpreted languages though as any decent compiler should be able to convert divisions to multiplication during optimization. The same should be true with this test — only a better compiler would be needed that can inline the pow() function then simplify it.
Once again, the test is using the I interpreter, a derivative of Lua and shares many of the same features. The I language also has a specialized integer power function which uses a loop to multiply up the given number. That will be tested alongside inline multiplication (should be the fastest since there is no loop) and floating point power (should be slowest).
// Power vs. Integer Power
// July 19, 2011use(“glut”)
local count = tonum(arg[1]) | 10000000 // ten million default// Integer Power
local a = glut.Get(“ELAPSED_TIME”)
for i = 0, count:
x = i ** 2
;
local ipow = glut.Get(“ELAPSED_TIME”) – a// Power
local a = glut.Get(“ELAPSED_TIME”)
for i = 0, count:
x = i ^ 2
;
local pow = glut.Get(“ELAPSED_TIME”) – a// Simple Multiply
local a = glut.Get(“ELAPSED_TIME”)
for i = 0, count:
x = i * i
;
local mul = glut.Get(“ELAPSED_TIME”) – a// Simple Multiply
local a = glut.Get(“ELAPSED_TIME”)
for i = 0, count:
x = i * i
;
local mul2 = glut.Get(“ELAPSED_TIME”) – a// Power
local a = glut.Get(“ELAPSED_TIME”)
for i = 0, count:
x = i ^ 2
;
local pow2 = glut.Get(“ELAPSED_TIME”) – a// Integer Power
local a = glut.Get(“ELAPSED_TIME”)
for i = 0, count:
x = i ** 2
;
local ipow2 = glut.Get(“ELAPSED_TIME”) – aoutln(“Integer Power 1: “, ipow * 0.001)
outln(“Integer Power 2: “, ipow2 * 0.001)
outln(“Power 1: “, pow * 0.001)
outln(“Power 2: “, pow2 * 0.001)
outln(“Multiplication 1: “, mul * 0.001)
outln(“Multiplication 2: “, mul2 * 0.001)
First off, before anyone disregards these results as invalid, the caret symbol (^) in I (and Lua) is NOT the bitwise exclusive or (XOR) like it is in C. No clue what I just said? Just keep reading…
Like last time, each result was computed twice. That reduces the error caused by the differences in the positions of each test.
Here are the results:
$ i powvsipow.ci
Integer Power 1: 0.992
Integer Power 2: 1.03
Power 1: 3.009
Power 2: 2.777
Multiplication 1: 0.839
Multiplication 2: 0.852
As expected, floating point power (denoted simply as “Power”) was the clear loser. It came in at over 3.5 times slower than inline multiplication which was the winner. Even for those who are unconcerned with speed, 3.5X is quite a bit. The integer power, though obviously slower than inline multiplication, is not slower by much. It’s a better option for those who are concerned with the appearance of a program where num * num * num * num * num * num is too messy (and long) for readability. Otherwise, consider inline multiplication next time you need to do an integer power.
