Which is better? Divide by 2 or multiply by 0.5?
barbara_morris 120000DX5W Visits (4139)
I recently got a note from Ted Holt of Four Hundred Guru asking whether the old rule about multiplication being faster than division still applies for RPG on IBM i.
For example, if you want to divide by two, this rule suggests that you should instead multiply by 0.5.
I have known of this rule for a long time, and I have been automatically following it, without wondering whether it was still necessary. I was reminded of of this
So I ran a little test to see if there's a difference. Yes, indeed, there is a difference. A loop with a million divides by 2 took 1.6 seconds and a loop with a million multiplies by 0.5 took 0.1 seconds. So it's true for the IBM i (not just for RPG) that multiplying is quicker than dividing.
Does this performance difference matter?
Maybe, if you are dividing a million times in a loop. Probably not, if you are just doing a few divisions as part of other business logic, especially if you are reading or writing files. And if it's really important for a particular scenario, make sure it applies for that scenario - maybe division by 2 would be different from division by 257.3.
But wait ... there's more ...
There is an RPG scenario where it's better to multiply than divide, and that's in complex expressions using RPG's default precision rules, where you want to divide by the result of a division.
x = y / (z / 100)
If you are using the default precision rules, the result of the z/100 division will have a size of say 63,58, maximizing the number of decimal places to get the most accurate division result. When you then divide that value again, the result will have a size of 63,0, with no decimal places.
Using the resu
(500 / (3 / 100) = 1666
D x s 25p 5
Here's what it displays:
DSPLY dft rules, / / : 16666.00000
Below is the program I used for the first performance test. It only tests one scenario at a time, so I can try what I think will be the faster scenario with more and more iterations until it runs long enough to be measurable. Then I try what I think is the slower scenario with that many iterations. Here's my session:
5 > call perfchk (1000 m)
Here's the program. Most of it can be used as a template for similar little tests.