Let’s say I want to divide two variables, in Python 2.* (mainly 6 and 7), that are considered integers. For instance:
a, b = 3, 2
print a/b
# Prints "1"
Now, there are at least two (non-redundant) ways I know of to cause this division to be normal, floating point division (without running a from __future__ import division). They are:
print a*1.0/b # Of course you could multiply b by 1.0 also
and
print float(a)/b # Here you could also have cast b as a float
Does one of these methods have an advantage (in speed) over the other? Does one have more overhead than the other?
From the above, you can tell that simply using
a*1.0/bis much faster then usingfloat(a). This is because calling functions in Python are very costly. That being said though, you could do something like:and you would have the benchmark of:
This is because you only call
float()once, and that is on assignment ofa. This in turn doesn’t require the1.0*ato be factored in, giving a much faster result.Breaking this down further using the
dismodule, you can see the actual calls for this in a loop:float during division
float during division dis results
Reason for speed decrease
The reason that this method is much slower is because it must first
LOAD_GLOBAL: float, then grab the value ofa(LOAD_FAST: a) then it callsfloat(a)(CALL_FUNCTION). It then finally executes the division (BINARY_DIVIDE), all of which done over and over during the loop.float on assignment
float on assignment dis results
Reason for speed increase
You can see that on the line in which the division is performed, it no longer has to call the float function, allowing immediate execution of the division. It simply calls
LOAD_GLOBAL: floatand callsCALL_FUNCTIONonce, which is on assignment, rather then in the loop. This means it can skip straight to theBINARY_DIVIDEcall.Stats used for this benchmark: