473,804 Members | 3,196 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Multiply float by -1: fast or slow?


Is this a fast way to invert a float:

inline Invert(float& f)
{
f *= -1.0f;
}

I'd like the CPU to flip the sign bit (and not carry out a float-float
multiplication) . Please enlighten me! I'm going be performing a lot
of these.

Thanks,

Chris

Jan 25 '07 #1
10 3914
Chris Stankevitz wrote:
Is this a fast way to invert a float:

inline Invert(float& f)
{
f *= -1.0f;
}

I'd like the CPU to flip the sign bit (and not carry out a float-float
multiplication) . Please enlighten me! I'm going be performing a lot
of these.

Thanks,

Chris
I think what you should do is:

inline Invert(float& f)
{
f = -f;
}
Jan 25 '07 #2
Chris Stankevitz wrote:
Is this a fast way to invert a float:

inline Invert(float& f)
Missing return type.
{
f *= -1.0f;
}

I'd like the CPU to flip the sign bit (and not carry out a float-float
multiplication) . Please enlighten me! I'm going be performing a lot
of these.
Try it, check the generated assembler. Your compiler should be able to
perform the required optimisation.

--
Ian Collins.
Jan 25 '07 #3
"Chris Stankevitz" <ch************ *@yahoo.comwrot e in message
news:11******** *************@k 78g2000cwa.goog legroups.com
Is this a fast way to invert a float:

inline Invert(float& f)
{
f *= -1.0f;
}

I'd like the CPU to flip the sign bit (and not carry out a float-float
multiplication) . Please enlighten me! I'm going be performing a lot
of these.

The only way to know is to test it. Different compilers will handle the same
code differently and different hardware platforms will have different
abilities.

On my computer

f = -f;

is slightly faster, but my computer can perform either operation about 100
million times per second. Code for testing:

#include <iostream>
#include <ctime>
using namespace std;

const int loops = 1000000000;

int main()
{
volatile float f = 345.898f;
int start = clock();
for(size_t i=0; i<loops; ++i)
f *= -1;
cout << ((double)clock( )-time)/CLOCKS_PER_SEC << endl;

start = clock();
for(size_t i=0; i<loops; ++i)
f = -f;
cout << ((double)clock( )-time)/CLOCKS_PER_SEC << endl;

return 0;
}

Note that tests like the above can't tell you exactly what speed you will
get in a real application, but they give you some idea.

--
John Carson
Jan 25 '07 #4
Roman S. wrote:
Chris Stankevitz wrote:
>Is this a fast way to invert a float:

inline Invert(float& f)
{
f *= -1.0f;
}

I'd like the CPU to flip the sign bit (and not carry out a
float-float multiplication) . Please enlighten me! I'm going be
performing a lot of these.

Thanks,

Chris

I think what you should do is:

inline Invert(float& f)
{
f = -f;
}
inline void Invert(float& f)
// ^^^^

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jan 25 '07 #5
Chris Stankevitz a écrit :
Is this a fast way to invert a float:

inline Invert(float& f)
{
f *= -1.0f;
}

I'd like the CPU to flip the sign bit (and not carry out a float-float
multiplication) . Please enlighten me! I'm going be performing a lot
of these.
If you don't mind portability, you can simply flip it:
reinterpret_cas t<char*>(&f)[sizeof(float)-1]^=0x80;

This is evil.

Michael
Jan 25 '07 #6
"John Carson" <jc************ ****@netspace.n et.auwrote in message
news:45******** *************** @uv-55king-reader-01.melbourne.pi penetworks.com. au
>
Code for testing:

#include <iostream>
#include <ctime>
using namespace std;

const int loops = 1000000000;

int main()
{
volatile float f = 345.898f;
int start = clock();
for(size_t i=0; i<loops; ++i)
f *= -1;
cout << ((double)clock( )-time)/CLOCKS_PER_SEC << endl;
// change time to start in previous line
start = clock();
for(size_t i=0; i<loops; ++i)
f = -f;
cout << ((double)clock( )-time)/CLOCKS_PER_SEC << endl;
// change time to start in previous line
return 0;
}

--
John Carson
Jan 25 '07 #7


On Jan 24, 11:07 pm, Michael DOUBEZ <michael.dou... @free.frwrote:
Chris Stankevitz a écrit :
Is this a fast way to invert a float:
inline Invert(float& f)
{
f *= -1.0f;
}
I'd like the CPU to flip the sign bit (and not carry out a float-float
multiplication) . Please enlighten me! I'm going be performing a lot
of these.If you don't mind portability, you can simply flip it:
reinterpret_cas t<char*>(&f)[sizeof(float)-1]^=0x80;

This is evil.

Not only is it not portable, it doesn't work on (probably) the majority
of architectures out there. Mind you that the OP did not specify that
he was running on x86 or another machine which has IEEE-like floats
stored little endian. Even worse, your code may be substantially
slower than just a straight multiplication by -1 or negation since it
will almost certainly force the compiler to actually store the value in
memory before flipping the bit - something that would likely be avoided
if the value was already in a register, and the function actual got (as
requested) inlined. All quite implementation dependent, of course.

Jan 25 '07 #8
Michael DOUBEZ wrote:
Chris Stankevitz a écrit :
>Is this a fast way to invert a float:

inline Invert(float& f)
{
f *= -1.0f;
}

I'd like the CPU to flip the sign bit (and not carry out a float-float
multiplication ). Please enlighten me! I'm going be performing a lot
of these.


If you don't mind portability, you can simply flip it:
reinterpret_cas t<char*>(&f)[sizeof(float)-1]^=0x80;
Don't try and 2nd guess the compiler when it comes to this sort of
optimisation.
This is evil.
It sure is.

--
Ian Collins.
Jan 25 '07 #9
ro***********@y ahoo.com a écrit :
>
On Jan 24, 11:07 pm, Michael DOUBEZ <michael.dou... @free.frwrote:
>Chris Stankevitz a écrit :
>>Is this a fast way to invert a float:
inline Invert(float& f)
{
f *= -1.0f;
}
I'd like the CPU to flip the sign bit (and not carry out a float-float
multiplicatio n). Please enlighten me! I'm going be performing a lot
of these.If you don't mind portability, you can simply flip it:
reinterpret_ca st<char*>(&f)[sizeof(float)-1]^=0x80;

This is evil.


Not only is it not portable, it doesn't work on (probably) the majority
of architectures out there. Mind you that the OP did not specify that
he was running on x86 or another machine which has IEEE-like floats
stored little endian. Even worse, your code may be substantially
slower than just a straight multiplication by -1 or negation since it
will almost certainly force the compiler to actually store the value in
memory before flipping the bit - something that would likely be avoided
if the value was already in a register, and the function actual got (as
requested) inlined. All quite implementation dependent, of course.
Yes, it is evil. But, if you do something implementation dependant, well
you just do it.

And I expect this kind of trick to work on IEEE, IBM and VAX float since
they all put the sign bit on the MSB. Making a switch for litlle/big
endian is not really a big deal.

Concerning the perfs, I didn't make any bench but the truth is that bit
operations on float are forbidden so unless the compiler optimize the
operation (-() or *-1.0f) alternatives are equivalent.

Now, this is not something I would do but worth a try.

Michael
Jan 25 '07 #10

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

Similar topics

13
2718
by: Link | last post by:
I have to convert an float number to int without using casting i= (int) f, without printf and others. I can only use int, char and structs. Can anyone help? Thanks Juerg
8
2892
by: Neil | last post by:
I have a very puzzling situation with a database. It's an Access 2000 mdb with a SQL 7 back end, with forms bound using ODBC linked tables. At our remote location (accessed via a T1 line) the time it took to go to a record was very slow. The go to mechanism was a box that the user typed the index value into a combo box, with very simple code attached: with me.RecordsetClone .FindFirst " = " & me.cboGoTo If Not .NoMatch Then Me.Bookmark...
22
3320
by: Marc Mones | last post by:
Hello, I'working with IBM DB2 V8.1 and CLI/ODBC. I've got a problem with the following statement: ******************************************************************************** SELECT S_ART, S_SPRACHE, S_MANDANT, S_NR, S_SUB, S_OWNER, S_SATZ FROM SY0001_00005 WHERE S_ART = ? AND S_SPRACHE = ? AND S_MANDANT = ? AND S_NR = ? AND
13
2726
by: Michele Guidolin | last post by:
Hello to everybody. I'm doing some benchmark about a red black Gauss Seidel algorithm with 2 dimensional grid of different size and type, I have some strange result when I change the computation from double to float. Here are the time of test with different grid SIZE and type: SIZE 128 256 512
5
9839
by: per.nordlow | last post by:
Hey there! I want to multiply/divide (shift) a float with variable containing a power-of-two value: 2, 4, 8, 16, .... Is there such a function in the C standard library or the glibc library that does this? If not has anybody written some clever high-performance "hack" like: 1. Cast float pointer to a 32-bit integer pointer.
0
4003
by: komandjaja | last post by:
Hi everybody. I am new here and I don't know much about CSS. However, I have a blog at multiply http://komandjaja.multiply.com and I have customized the CSS codes there to make a new theme. When I see my page thru Firefox, everything is okay but when I see it with IE, there are distorted things and some pictures don't show up. My platform is Windows XP home edition. Here's my css code to the site /************* Spiderman 3...
13
6196
by: Shirsoft | last post by:
I have a 32 bit intel and 64 bit AMD machine. There is a rounding error in the 8th digit. Unfortunately because of the algorithm we use, the errors percolate into higher digits. C++ code is ------------------ b += (float)(mode *val); On 32 bit(intel , vs 2003, C++), some watch variables are
3
10671
by: Arnie | last post by:
Folks, We ran into a pretty significant performance penalty when casting floats. We've identified a code workaround that we wanted to pass along but also was wondering if others had experience with this and if there is a better solution. -jeff
9
2150
by: Salad | last post by:
I have access, for testing at my client's site, a Win2000 computer running A2003 retail. He recently upgraded all of his other machines to DualCore Pentiums with 2 gig ram and run A2003 runtime. I believe all current SPs for Windows and Office are installed on the fast machines. I have 1 process/subroutine that has worked for a couple of years without a problem. It works fine on the testing (slow) machine. The process checks a folder...
0
10332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10321
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
9152
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...
0
6853
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
5522
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...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.