473,799 Members | 3,224 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Multiplication optimization

Does Python's run-time do any optimization of multiplication
operations, like it does for boolean short-cutting? That is, for a
product a*b, is there any shortcutting of (potentially expensive)
multiplication operations as in:

if a == 0
return 0
if a == 1
return b
return a*b

Of course, for the cases where a is not 0 or 1 we are adding two
comparisons to each multiply operation. But in some applications
(sparse matrices? binary conversion?), the multiplication step could be
avoided in many cases, if the user was aware that left-to-right
short-cutting were implemented.

Or by adding two *more* comparisons, then all multiplications would be
"optimized" :

if a == 0 or b == 0
return 0
if a == 1
return b
if b == 1
return a
return a*b

But this seems overkill, especially since boolean short-cutting only
works left-to-right.

Just curious...

-- Paul

Feb 19 '06 #1
5 1568
On Sat, 18 Feb 2006 16:48:38 -0800, Paul McGuire wrote:
Does Python's run-time do any optimization of multiplication
operations, like it does for boolean short-cutting?


Do you know that these shortcuts are optimizations, or are you just
assuming it takes less time to do the comparison than it would for the
CPU to blast bits around?

I have no idea whether your shortcuts are optimizations or pessimizations.
I'm just asking whether you know, or if you are making assumptions.
--
Steven.

Feb 19 '06 #2
[Paul McGuire]
Does Python's run-time do any optimization of multiplication
operations, like it does for boolean short-cutting?


Usually, it is safest (and typically true) to assume that Python
performs no optimizations. To go beyond making assumptions, it is easy
to run a few timings:
from timeit import Timer
min(Timer('0*12 34567').repeat( 5)) 0.1131537667496 8469 min(Timer('1*12 34567').repeat( 5)) 0.1192045357720 0618 min(Timer('113* 1234567').repea t(5))

0.1188148214368 0699

In your specific case, I can answer than the source shows no special
optimization for multiplications by specific values. There is a
short-path for integer multiplications but it is not value specific.
In Py2.5, the compiler will do a limited amount of constant folding;
however, its scope is somewhat limited because expressions like a*3
vary depending on the a's type which is often not knowable by the
compiler without some form of global analysis.

One other thought: Python is not assembly. Run time is unlikely to be
dominated by the time to execute a multiplication. With Python, it is
best to focus optimization efforts on making choosing the best data
structures and hoisting constants out of loops.
Raymond

Feb 19 '06 #3
Paul McGuire wrote:
Does Python's run-time do any optimization of multiplication
operations, like it does for boolean short-cutting? That is, for a
product a*b, is there any shortcutting of (potentially expensive)
multiplication operations


no. and the reason is very simple: to the extent such optimization
makes sense, it has been done on assembler/CPU level already. i.e. when
the multiplication is mapped to the machine code
IMUL <op>
the Pentium processor would be smart enough not to do the work if AX or
the op are 0 or 1.

Python has no job trying to outsmart Intel (and the other chipmakers).
Boolean shortcuts are useful for entirely different reason, not speed.
e.g.
if lastDigit == 0 or i % lastDigit != 0:
break

if both operands of OR were to be evaluated, that would end up with
division-by-zero exception for lastDigit=0.

Feb 19 '06 #4
Atanas Banov wrote:
Paul McGuire wrote:
Does Python's run-time do any optimization of multiplication
operations, like it does for boolean short-cutting? That is, for a
product a*b, is there any shortcutting of (potentially expensive)
multiplication operations


no. and the reason is very simple: to the extent such optimization
makes sense, it has been done on assembler/CPU level already. i.e. when
the multiplication is mapped to the machine code
IMUL <op>
the Pentium processor would be smart enough not to do the work if AX or
the op are 0 or 1.

Python has no job trying to outsmart Intel (and the other chipmakers).
Boolean shortcuts are useful for entirely different reason, not speed.
e.g.
if lastDigit == 0 or i % lastDigit != 0:
break

if both operands of OR were to be evaluated, that would end up with
division-by-zero exception for lastDigit=0.


The point is not to avoid the multiplication on the CPU level but the object
creation overhead:
a = 1234
1 * a is a

False # could be True
$ python -m timeit -s'a=1;b=1234567 ' 'if a is 1: x = b' 'else: x = a * b'
10000000 loops, best of 3: 0.171 usec per loop
$ python -m timeit -s'a=1;b=1234567 ' 'x = a * b'
1000000 loops, best of 3: 0.211 usec per loop
$ python -m timeit -s'a=2;b=1234567 ' 'if a is 1: x = b' 'else: x = a * b'
1000000 loops, best of 3: 0.329 usec per loop

If 'a is 1' is sufficiently likely, that test speeds up the code even in
pure Python. Of course a generalized implementation would also have to
check b's type:

$ python -m timeit -s'a=1;b=1234567 ' 'if a is 1 and b.__class__ is int: x =
b' 'else: x = a * b'
1000000 loops, best of 3: 0.484 usec per loop

So that is not a good idea, at least in pure Python.

Peter

Feb 20 '06 #5
"Paul McGuire" <pt***@austin.r r.com> wrote:

Does Python's run-time do any optimization of multiplication
operations, like it does for boolean short-cutting? That is, for a
product a*b, is there any shortcutting of (potentially expensive)
multiplicati on operations as in:


Integer multiplication is a 1-cycle operation in Intel processors.

Even multiple-precision multiplication is very efficient -- probably more
so than multiple comparisons and jumps.
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Feb 21 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2049
by: I.V. Aprameya Rao | last post by:
hi i have been wondering, how does python store its very long integers and perform aritmetic on it. i needed to implement this myself and was thinking of storing the digits of an integer in a list. however this would be very slow for operations like division etc.
11
2553
by: Michael Bader | last post by:
Hi, I'm currently working on a matrix multiplication code (matrix times matrix), and have come along some interesting/confusing results concerning the running time of the (apparently) same algorithm, when implemented in C or C++. I noticed that the implementation in C is faster by a factor of 2.5 compared to a identical(?) C++-implementation. The basic algorithm in C is:
54
8380
by: Andy | last post by:
Hi, I don't know if this is the correct group to post this, but when I multiply a huge floating point value by a really small (non-zero) floating point value, I get 0 (zero) for the result. This creates a big hole in a 32-bit timer routine I wrote. Questions. 1. Why does this happen? 2. Is there C macros/functions I can call to tell me when two non-zero numbers are multiplied and the
9
8003
by: Ralf Hildebrandt | last post by:
Hi all! First of all: I am a C-newbie. I have noticed a "strange" behavior with the standart integer multiplication. The code is: void main(void)
87
11249
by: Vijay Kumar R Zanvar | last post by:
Hi, Why multiplication of pointers is not allowed? Till now I only know this, but not the reason why! PS: As a rule, I searched the FAQ, but could not find an answer. -- Vijay Kumar R Zanvar
17
8029
by: Christopher Dyken | last post by:
Hi group, I'm trying to implement two routines to handle 32x32-bits and 64x64-bits signed integer multiplication on a 32 bits machine in C. It easy to find descriptions of non-signed multiplication, however, I haven't found any good descriptions for the signed counterpart. Does any of you have a good reference for this topic? Thanks in advance,
4
1978
by: Yixin Cao | last post by:
GCC always avoids multiplication instructions as much as possible, so a *= 10; will be translated into: leal (%eax, %eax, 4), %eax add %eax, %eax I do know that it is due to historic reason, for that old CPU spent 30+ clock cycles to finish a multiplication instruction. But it is never true now, while 3 clock cycles will suffice, so it brings the side affect of bigger object files without any gain. It might do it default for the...
7
7591
by: VijaKhara | last post by:
Hi all, Is there any method which can implememt the matrix multiplication faster than using the formula as we often do by hand? I am writing the following code and my matrice: one is 3x40000 and the other one 40000x3. the program runs too slow: /*multiply two matrice: xyz_trans * xyz , the output is w 3x3*/
1
9170
by: Sozos | last post by:
Hi guys. I have a problem with writing the base case for the following matrix multiplication function I have implemented. Please help. #define index(i,j,power) (((i)<<(power))+(j)) void recMultiply(int i, int j, float a, int k, int l, float b, int x, int y, float c, int s); int i, j, k, s, matrixsize, blocksize, jj, kk, power, bsize; float sum, maxr, total=0.0, startmult, finishmult, multtime; float* A = NULL; float* B = NULL;
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10470
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10214
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10023
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9067
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7561
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6803
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5459
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3751
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.