473,762 Members | 6,570 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

the fastest way to do an odd/even check?

Hi,

I have a question, which is just out of interest.
What is the fastest way to do an odd/even check with c++ and if needed
assembler.

Assume n is an unsigned integer like type (unsigned int, unsigned long
int), what is the fastest?

using the modulo operator

a) if (n%2 == 0) then even
b) if (n%2 == 1) then odd
c) if (n%2 != 1) then even
d) if (n%2 != 0) then odd

using the bit shift operator

e) if ((n >1) << 1 == n) then even
f) if ((n >1) << 1 != n) then odd
g) if (((n >1) << 1) - n == 0) then even
h) if (n - ((n >1) << 1) == 1) then odd

They always told me that checking against '0' is the best for "speed",
if you can call it speed here ;-), thus this rules out b and c for sure.

But what would it be? I think bitshifts are faster then modulo
calculations. Is this right?

The most fast would be checking the last bit in the binary array. Is it
1, then it is odd else it is even. Can you do bitchecks in a number
with c++?

I can think of a rule, assume you want to check bit 5, you can do

n & (1<<5) == (1<<5)

but this is for sure not faster then just reading the bit. Because you
do 64 operations with the & and 64 operations with the checking, which
is much more then 2 operations.

So I was just wondering.
Anybody an idea?

Thanks
Klaas
Feb 1 '07 #1
6 50274
* Klaas Vantournhout:
Hi,

I have a question, which is just out of interest.
What is the fastest way to do an odd/even check with c++ and if needed
assembler.

Assume n is an unsigned integer like type (unsigned int, unsigned long
int), what is the fastest?

using the modulo operator

a) if (n%2 == 0) then even
b) if (n%2 == 1) then odd
c) if (n%2 != 1) then even
d) if (n%2 != 0) then odd

using the bit shift operator

e) if ((n >1) << 1 == n) then even
f) if ((n >1) << 1 != n) then odd
g) if (((n >1) << 1) - n == 0) then even
h) if (n - ((n >1) << 1) == 1) then odd

They always told me that checking against '0' is the best for "speed",
if you can call it speed here ;-), thus this rules out b and c for sure.

But what would it be? I think bitshifts are faster then modulo
calculations. Is this right?

The most fast would be checking the last bit in the binary array. Is it
1, then it is odd else it is even. Can you do bitchecks in a number
with c++?

I can think of a rule, assume you want to check bit 5, you can do

n & (1<<5) == (1<<5)

but this is for sure not faster then just reading the bit. Because you
do 64 operations with the & and 64 operations with the checking, which
is much more then 2 operations.

So I was just wondering.
Anybody an idea?
The assumptions about speeds of various operations above are plain
wrong. It depends on the compiler and the computer (and more). Also,
the assumptions about number of operations involved in bit shifting are
plain wrong.

Don't try to optimize at this level: let the compiler do it. If you
think you have to optimize, first /measure/. And that doesn't mean
measuring operations, it means measuring where your code spends its
time, i.e. getting hard data on what may benefit from optimization.

Even better, don't try to optimize basic operations, at all, but do
choose reasonably efficient algorithms.

Finally, please read the FAQ before posting.

The FAQ contains much good advice, I believe also about the above.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 1 '07 #2
On Feb 1, 3:29 pm, Klaas Vantournhout <no_valid_em... @spam.comwrote:
Hi,

I have a question, which is just out of interest.
What is the fastest way to do an odd/even check with c++ and if needed
assembler.

Assume n is an unsigned integer like type (unsigned int, unsigned long
int), what is the fastest?

using the modulo operator

a) if (n%2 == 0) then even
b) if (n%2 == 1) then odd
c) if (n%2 != 1) then even
d) if (n%2 != 0) then odd
I would assume all of those to take the same amount of time on a
modern CPU, though see my comment on comparing against 0 a bit down.
e) if ((n >1) << 1 == n) then even
f) if ((n >1) << 1 != n) then odd
g) if (((n >1) << 1) - n == 0) then even
h) if (n - ((n >1) << 1) == 1) then odd
These does not look particularly fast to me, many operations. But it
might be faster than modulo, I don't know how that's done in the CPU.
They always told me that checking against '0' is the best for "speed",
if you can call it speed here ;-), thus this rules out b and c for sure.

But what would it be? I think bitshifts are faster then modulo
calculations. Is this right?
On some CPUs there's a special register for the value 0 while other
values might have to be loaded into a register first.
The most fast would be checking the last bit in the binary array. Is it
1, then it is odd else it is even. Can you do bitchecks in a number
with c++?
Bitwise compare:
if (n | 0x1) then odd
this is probably the fastest way.
I can think of a rule, assume you want to check bit 5, you can do

n & (1<<5) == (1<<5)
Better would be
if (n | 0x10)
>
but this is for sure not faster then just reading the bit. Because you
do 64 operations with the & and 64 operations with the checking, which
is much more then 2 operations.
64 operations? Shifting is 1 operation and & is one operation and
compare is 1, since there are two shifts that adds up to 4 operations.
So I was just wondering.
Anybody an idea?
If you are wondering these kinds of things you should either go and
read up some on how computers works and assembly programming. Or you
are trying to optimize something, in which case I'd advice you to do
some profiling before trying to speed up that operation, it's most
probably not the slowest one in a program.

If you want to know how these things work on modern CPUs you can
download a lot of stuff from Intel: http://www.intel.com/products/proces...uals/index.htm

Feb 1 '07 #3
Erik Wikström wrote:
If you are wondering these kinds of things you should either go and
read up some on how computers works and assembly programming. Or you
are trying to optimize something, in which case I'd advice you to do
some profiling before trying to speed up that operation, it's most
probably not the slowest one in a program.

If you want to know how these things work on modern CPUs you can
download a lot of stuff from Intel: http://www.intel.com/products/proces...uals/index.htm
Thanks for your response Erik,

It was for sure not my intention of optimizing this, but it was just a
curiosity! You are absolutely right that this is more related to the
compiler, assembler and the CPU.

If that process would have been the slowest process in the code ... then
I can imagine that something is seriously wrong with the code ;-)

regards

Klaas

Feb 1 '07 #4
JLS
On Feb 1, 9:29 am, Klaas Vantournhout <no_valid_em... @spam.comwrote:
Hi,

I have a question, which is just out of interest.
What is the fastest way to do an odd/even check with c++ and if needed
assembler.

Assume n is an unsigned integer like type (unsigned int, unsigned long
int), what is the fastest?

using the modulo operator

a) if (n%2 == 0) then even
b) if (n%2 == 1) then odd
c) if (n%2 != 1) then even
d) if (n%2 != 0) then odd

using the bit shift operator

e) if ((n >1) << 1 == n) then even
f) if ((n >1) << 1 != n) then odd
g) if (((n >1) << 1) - n == 0) then even
h) if (n - ((n >1) << 1) == 1) then odd

They always told me that checking against '0' is the best for "speed",
if you can call it speed here ;-), thus this rules out b and c for sure.

But what would it be? I think bitshifts are faster then modulo
calculations. Is this right?

The most fast would be checking the last bit in the binary array. Is it
1, then it is odd else it is even. Can you do bitchecks in a number
with c++?

I can think of a rule, assume you want to check bit 5, you can do

n & (1<<5) == (1<<5)

but this is for sure not faster then just reading the bit. Because you
do 64 operations with the & and 64 operations with the checking, which
is much more then 2 operations.

So I was just wondering.
Anybody an idea?

Thanks
Klaas
I worked at one job where this was a standard interview question, but
that was many languages, many computers, and many years ago. It
started a discussion of all the ways one could test for odd/even. Some
languages contain an "IsOdd" method. The usual method at the time was
to divide by 2, multply by two and see if you have the same number
(even) or not (odd). Back then, there were different method of storing
numbers so the shift method was not portable. When the moduler
operation became standard, some people shifted to that.

btw: The slowest method that I ever saw implemented was to subtract 2
over and over again until the number was less than two and then the
result was compared to 1. Needless to say, the implementer became an
ex-programmer.

Feb 1 '07 #5
"Erik Wikström" <er****@student .chalmers.sesch rieb im Newsbeitrag
news:11******** **************@ a75g2000cwd.goo glegroups.com.. .
>using the modulo operator

a) if (n%2 == 0) then even
b) if (n%2 == 1) then odd
c) if (n%2 != 1) then even
d) if (n%2 != 0) then odd

I would assume all of those to take the same amount of time on a
modern CPU, though see my comment on comparing against 0 a bit down.
>e) if ((n >1) << 1 == n) then even
f) if ((n >1) << 1 != n) then odd
g) if (((n >1) << 1) - n == 0) then even
h) if (n - ((n >1) << 1) == 1) then odd

These does not look particularly fast to me, many operations. But it
might be faster than modulo, I don't know how that's done in the CPU.
....
Bitwise compare:
if (n | 0x1) then odd
this is probably the fastest way.
This is probably the fastes of all operations mentioned here. Any decent
compile should recognize that n|1 is always true.
>I can think of a rule, assume you want to check bit 5, you can do

n & (1<<5) == (1<<5)

Better would be
if (n | 0x10)
Both look terrible, but the second is plain wrong. To test a single bit you
have to use & instead of |. Using | with a non-zero constant will give a
non-zero result. My prefered way to test the state of the single bit is

if (n & (1 << x)) // even if x is 0

If the compiler cannot replace such constant sub-expressions at compile
time, it shouldn't be used at all. Even the oldest C compilers could do
that.

To the OP: Most modern compilers should recognize what expressions like n%2
or n&1 are suposed to do and optimize them, probably to the same code. So
use whatever is more readable to you and those (humans) who are supposed to
read your code. Using % looks like a mathmatican's approach, & like an
assembly language programmer's. The shifting orgy in e - g, however, looks
like a mad sicentist's code.

Heinz
Feb 1 '07 #6

"Heinz Ozwirk" <SP*********@ar cor.dewrote in message
news:45******** *************** @newsspool4.arc or-online.net...
"Erik Wikström" <er****@student .chalmers.sesch rieb im Newsbeitrag
news:11******** **************@ a75g2000cwd.goo glegroups.com.. .
>Better would be
if (n | 0x10)

Both look terrible, but the second is plain wrong. To test a single bit
you have to use & instead of |.
Indeed. Besides, 1<<5 == 0x20, not 0x10
>
To the OP: Most modern compilers should recognize what expressions like
n%2 or n&1 are suposed to do and optimize them, probably to the same code.
For unsigned integers, perhaps, but certainly not always for signed integers
as -1 % 2 == -1 on most architectures.

- Sylvester
Feb 2 '07 #7

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

Similar topics

9
32647
by: Rune Strand | last post by:
Hi, If I have a lot of integers and want do something with each digit as integer, what is the fastest way to get there? Eg. Make 12345 into an iterable object, like or "12345" (Btw: What is the English term for this process; itemize? tokenize? digitize? sequence?) Some examples:
1
1441
by: Tim Arnold | last post by:
Hi, I've got a list of 1000 common misspellings, and I'd like to check a set of text files for those misspellings. I'm trying to figure out the fastest way to do it; here's what I'm doing now (below). I'm still learning Python, love it, and I'm pretty sure that what I'm doing is naive. Thanks for taking the time to look at this,
8
3055
by: David P. Jessup | last post by:
Well I have seen this posted before and haven't seen much in response. My application has to browse through various folders and find file names. Sometimes these folders can have thousands of files in them, and of course looping through each file to find the right one can take a bit of time. I'm using classic ASP and was wondering if there are any other methods available to speed up this process other than hardware upgrades. My...
17
2328
by: DraguVaso | last post by:
Hi, I need to find the FASTEST way to get a string in a Loop, that goes from "a" to "ZZZZZZZZZZZZZZZZZ". So it has to go like this: a b .... z
11
3618
by: hoopsho | last post by:
Hi Everyone, I am trying to write a program that does a few things very fast and with efficient use of memory... a) I need to parse a space-delimited file that is really large, upwards fo a million lines. b) I need to store the contents into a unique hash. c) I need to then sort the data on a specific field. d) I need to pull out certain fields and report them to the user.
3
21367
by: Lance | last post by:
What is the fastest way to determine if two arrays that contain ValueTypes are equal? For example, lets say I have the following: Dim pt1 as New Drawing.Point(1, 2) Dim pt2 as New Drawing.Point(2, 3) Dim pt3 as New Drawing.Point(3, 4) Dim pt4 as New Drawing.Point(4, 5) Dim A() as Drawing.Point = {pt1, pt2, pt3}
12
6461
by: Vjay77 | last post by:
Hi, I haven't posted any problem in quite a while now, but I came to the point that I really need to ask for help. I need to create an application which will search through .txt log file and find all lines where email from hotmail occured. All these emails need to be printed to list box on the form. Problem with code you'll see below, is that it takes long time to
17
3260
by: wswilson | last post by:
In python, I could write: a = 1 if a in : do something... In c (and many other languages):
0
2323
by: dantz | last post by:
After reading all of the materials in msdn about interprocess communication now I am confused. I hope someone can give me some enlightment. I am developing a multithreaded client-server application which communicates via HTTP Request using HTTPListener/HTTPWebRequest. The server(which is the focus of my question) will be having different modules. I want these modules to communicate with each other using the fastest IPC but I can't figure...
0
9989
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...
0
9812
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
8814
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
7360
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
6640
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
5268
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
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
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.