|
|
View previous topic :: View next topic |
Author |
Message |
evsource
Joined: 21 Nov 2006 Posts: 129
|
Fixed vs Floating point - is faster possible? |
Posted: Tue Nov 03, 2009 11:02 am |
|
|
Hi,
I know the benefits of fixed point vs. floating point calculations. I have code that needs to run as fast as possible, so I try to write the fastest code possible. I'm wondering if anyone can improve on the following example (let's assume a 18F chip at 40mHz).
Let's say I need to do this calculation:
(160 / 360) * 636
First, floating point:
Code: |
int16 first, second, third;
first = 160;
second = 360;
third = 636;
(int16)(((float)first / (float) second) * (float) third)
|
The divide will cost about 145us, and the multiply 36us, for 181us (assuming the casts consume a negligible amount of time).
Now, my fixed point version:
This is what I'm doing: ((160 * 1024 / 360 ) * 636 ) / 1024
And the code:
Code: |
int16 first, second, third;
first = 160;
second = 360;
third = 636;
(int16)((((((int32) first) << 10) / second) * (int16)third) >> 10 );
|
That has an int32 divide at 107us, and a int32 multiply at 22us, for a total of 129us. This assumes that the bit shifting and casts take a negligible amount of time.
I'm sure it can be done even faster. Anyone have any ideas? |
|
|
mskala
Joined: 06 Mar 2007 Posts: 100 Location: Massachusetts, USA
|
|
Posted: Tue Nov 03, 2009 12:38 pm |
|
|
Two comments:
1) This type of thing is very dependent on what fits into the variable size
in intermediate steps, so it is not so general that a future user could
just send any old values into a function using it.
2) Faster would be to identify what values are 'constants' of the calculations,
condense those down to a single operation. If you have a hardware
multiplier in your pic, then you're pretty much done. If not, then see
what bit shifts can be done to accomplish without any multiply or divide.
Meaning, you only multiply or divide by powers of 2 which are then
added or subtracted. (Check in a spreadsheet if the error is
acceptable over entire range of values, because it can deal with round-
off errors).
Mark S. |
|
|
Ttelmah Guest
|
|
Posted: Wed Nov 04, 2009 3:45 am |
|
|
Also, you have already identified one big speed difference in float. Multiplication is always a lot faster than division. So, can you re-design what you want to do to use multiplication by a reciprocal value?. Obvously with the constant values shown, this is easy, but in a real operation, with variables, it may still be possible.
Best Wishes |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|