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

Home Posts Topics Members FAQ

From bool to int: 1 or 0


If I wanted a super-efficient algorithm for counting the amount of 6's in
an array, (given the address of the first element and the amount of
elements), I might start off with:

#include <cstddef>

unsigned AmountSixes( const int *p, std::size_t const len )
{
unsigned amount = 0;

const T* const p_over = array + len;

do
{
if( *p++ == 6 ) ++amount;
}
while ( p != p_over );

return amount;
}
However, by my own coding style, I'd probably change the loop to:

do
{
amount += (*p++ == 6);
} while ( p != p_over );
This would rely on the bool to int conversion which would yield 1 or 0.

Any thoughts on which would be likely to be more efficient on the
majority of architectures if I was writing fully portable code to be used
on everything from a wristwatch to a personal computer?


--

Frederick Gotham
Jun 16 '06 #1
16 2704
Frederick Gotham wrote:
If I wanted a super-efficient algorithm for counting the amount of
6's in an array, (given the address of the first element and the
amount of elements), I might start off with:
Or you might use 'std::count'...

#include <cstddef>

unsigned AmountSixes( const int *p, std::size_t const len )
{
unsigned amount = 0;

const T* const p_over = array + len;

do
{
if( *p++ == 6 ) ++amount;
}
while ( p != p_over );

return amount;
}
However, by my own coding style, I'd probably change the loop to:

do
{
amount += (*p++ == 6);
} while ( p != p_over );
Why bother when there is 'std::count'? :-)
This would rely on the bool to int conversion which would yield 1 or
0.
It does.
Any thoughts on which would be likely to be more efficient on the
majority of architectures if I was writing fully portable code to be
used on everything from a wristwatch to a personal computer?


return std::count(p, p + len, 6)

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 16 '06 #2
Victor Bazarov posted:

return std::count(p, p + len, 6)

Thanks for the input, Victor. Checking for the quantity of instances of a
particular elemental value was just an example.

The main point of my post was to discuss which of the following two
approaches would be preferable in everyday programming:

if( *p++ == 6 ) ++amount;

or:

amount += (*p++ == 6);

--

Frederick Gotham
Jun 16 '06 #3
Frederick Gotham wrote:
Victor Bazarov posted:

return std::count(p, p + len, 6)

Thanks for the input, Victor. Checking for the quantity of instances of a
particular elemental value was just an example.

The main point of my post was to discuss which of the following two
approaches would be preferable in everyday programming:

if( *p++ == 6 ) ++amount;

or:

amount += (*p++ == 6);


In an effort to say what you mean I prefer the former; it says exactly
what is intended. The later is more cryptic and full of trickery. The
fact that you have to ask only proves the point.

Jun 16 '06 #4
Frederick Gotham wrote:
The main point of my post was to discuss which of the following two
approaches would be preferable in everyday programming:

if( *p++ == 6 ) ++amount;

or:

amount += (*p++ == 6);


I would say the former since it is more readable and likely of
negligible performance difference. The meaning of the first is obvious
even to a junior programmer, while one must decode the second, and
programmers have enough to worry about without trying to determine if
an unnecessarily clever statement like that is causing problems.

Cheers! --M

Jun 16 '06 #5

In response to both Noah and mlimber,

I am not at all bothered with whether one form is easier to understand
than the other -- I am solely concerned with performance.

If I wanted to simplify it, I could write a macro or a template function.

I suppose I could rephrase my question as follows:

Which of the following two macros would be preferable (performance-wise)
for use in portable code?:
#define IncrementIfTrue (amount,true_or _false)\
{ amount += static_cast<boo l>( true_or_false ); }
#define IncrementIfTrue (amount,true_or _false)\
{ if ( true_or_false ) ++amount; }
To be used as follows:

#include <cstddef>

unsigned AmountSixes( const int *p, std::size_t const len )
{
unsigned amount = 0;

const T* const p_over = array + len;

do
{
IncrementIfTrue ( amount, *p++ == 6 );
}
while ( p != p_over );

return amount;
}
--
Frederick Gotham
Jun 16 '06 #6
#define IncrementIfTrue (amount,true_or _false)\
{ amount += static_cast<boo l>( true_or_false ); }

I must admit that I'm slightly unsure as to whether this will be as
efficient as I think it will. I wonder if the compiler would treat it
something like:

#define IncrementIfTrue (amount,true_or _false)\
{ amount += ( true_or_false ? 1 : 0 ); }
This might even be more costly than a simple "if" statment... Would it?

--

Frederick Gotham
Jun 16 '06 #7
Frederick Gotham wrote:
#define IncrementIfTrue (amount,true_or _false)\
{ amount += static_cast<boo l>( true_or_false ); }

I must admit that I'm slightly unsure as to whether this will be as
efficient as I think it will. I wonder if the compiler would treat it
something like:

#define IncrementIfTrue (amount,true_or _false)\
{ amount += ( true_or_false ? 1 : 0 ); }
This might even be more costly than a simple "if" statment... Would
it?


Might. Or might not. If you are "solely concerned with performance",
measure it, don't guess. However, I bet that when the entire program
is measured, the difference between the two methods is going to be
negligible.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 16 '06 #8
Frederick Gotham wrote:
In response to both Noah and mlimber,

I am not at all bothered with whether one form is easier to understand
than the other -- I am solely concerned with performance.
Different compilers (and optimizers!) will produce different code, and
some CPU architectures and memory/cache configurations may do some
things more efficiently than others. So there's really no way to
determine which is faster in general. You could use a profiler on your
particular system to see which is faster on that system, but I strongly
suspect you're barking up the old "premature optimization" tree (see,
e.g., "Beware Premature Optimization" in
http://www.gotw.ca/publications/mill09.htm).

If I wanted to simplify it, I could write a macro or a template function.

I suppose I could rephrase my question as follows:

Which of the following two macros would be preferable (performance-wise)
for use in portable code?:
#define IncrementIfTrue (amount,true_or _false)\
{ amount += static_cast<boo l>( true_or_false ); }
#define IncrementIfTrue (amount,true_or _false)\
{ if ( true_or_false ) ++amount; }
To be used as follows:

#include <cstddef>

unsigned AmountSixes( const int *p, std::size_t const len )
{
unsigned amount = 0;

const T* const p_over = array + len;

do
{
IncrementIfTrue ( amount, *p++ == 6 );
}
while ( p != p_over );

return amount;
}


First of all, macros should be avoided when possible because of all
their "issues" (see
http://www.parashift.com/c++-faq-lit....html#faq-9.5).

Second, using a macro or inline function or your clever code here just
obfuscates your meaning again. Write code for humans, not the CPU (let
the compiler/optimizer worry about that!), until you have measured (not
intuited!) that hand optimizing would be of significant benefit.

Cheers! --M

Jun 16 '06 #9

Frederick Gotham wrote:
In response to both Noah and mlimber,

I am not at all bothered with whether one form is easier to understand
than the other -- I am solely concerned with performance.
http://www.flounder.com/optimization.htm
http://en.wikipedia.org/wiki/Optimiz...en_to_optimize

Since you are asking about the performance of these different methods I
must assume you have NOT gathered data yet.
Which of the following two macros would be preferable (performance-wise)
for use in portable code?:
#define IncrementIfTrue (amount,true_or _false)\
{ amount += static_cast<boo l>( true_or_false ); }
#define IncrementIfTrue (amount,true_or _false)\
{ if ( true_or_false ) ++amount; }


Without data I can only guess. My guess is on the later. Reasons:

* In the former the addition is always performed.
* The former requires the loading and addition of two registers, the
later does not.
* The former requires a cast.
* The former requires an additional assignment.

Now, the compiler could eliminate all those differences. The compiler
will have an easier time figuring out how to optimize when the code is
easier to interpret. The compiler was written by a human, therefor
things a human finds easier to interpret are more likely programmed
into the compiler's logic.

Stop trying to second guess your compiler before you even start.
Chances are very high that you are not smarter than the people that
wrote it. By trying to outwhit the experts you are more likely than
not to hinder the compiler's ability to optimize for you.

Jun 16 '06 #10

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

Similar topics

0
270
by: Doug | last post by:
I am working on an existing .NET (C Sharp) component that had a com interface that was used by a VB component. When it was originally written, it had the SSEAssemblyCom class below - minus the two last methods (for space I modified method names in my example below). I added those. Everything but the two new methods I added referenced the ISSEAssemblyCom interface below. I was told I would need to create a secondary interface...
0
1958
by: Jacek | last post by:
Hi If it is wrong newsgroup, please let me know where to find the answer. I am trying to get item text form ListView (there are few items and 5 columns) from other application (application written in MFC). As I know I have to allocate memory in target application address space, send a message and than read from allocated memory. But I still doing something wrong and can't find correct solution. I fell I am close to it. Please find code...
3
2613
by: Pierre Espenan | last post by:
A have a long integer class. The built integer type within a conditional statement returns bool false for int i=0 and bool true for any other non zero value. I want my long integer class to have similar behavior. My class looks like this: #ifndef long_int_H #define long_int_H #include <string> using namespace std; typedef valarray<complex<double> > VCD;
4
2953
by: Nomak | last post by:
Hello, With this code: $ cat -n ifs.cc 1 #include <vector> 2 #include <iostream> 3 4 using std::vector; 5 using std::cin;
1
1285
by: =steFF= | last post by:
Hi, I am trying to print the values I have in a vector and my compiler says: error C2227: left of '->printLn' must point to class/struct/union on this instruction: m_data->printLn(); (in my file pile.h) Can someone tell why it says that? Also, I don't understand why I am not allowed to put const on this method: void printLn(); when I write void printLn() const; It says : 'printLn' : overloaded member
0
3485
by: Jim dunn | last post by:
HI I am having problems with C# with regards to its compatibility with win32 API methods, I am trying to read from a windows CE comm port using C# and imported methods from coredll.dll, it seems that I can set the comm state however when I try and read from the port using ReadFile method I cannot, I've tried to change the DCB object flag types but this does not make a difference as I still cannot read from the port. I have pasted my code...
2
5949
by: David | last post by:
hello... how can i use IActiveDesktop COM interface from shell32.dll? thanx...
9
7919
by: John Howard | last post by:
How can I read a text file that is on a UNIX server in VB.Net? Please keep it simple. Thanks, John
7
3879
by: John.NET | last post by:
Hi, First please forgive that this is a repost as the first time I didn't have my proper nospam email configured... I'm writing a web service where one method will launch another .NET program under a specified user's account. It launches fine as the NT AUTHORITY\NETWORK SERVICE user when I dont specify a username/password for the ProcessStartInfo but I am having trouble getting it to work when I specify any other username/password...
12
3542
by: Howard Swope | last post by:
This problem has been bugging me for a while. I have created a collection class and implemented it in a C# library. If I inherit from this class in another C# assembly and it works, but if I inherit from this class in a C++ / CLI assembly it won't compile. This indicates a problem in the CLR. Can anyone shed some light on this. The class follows: public abstract class DictionaryBase<TKey,TValue: IDictionary<TKey,TValue>,
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10577
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...
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
10320
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
9150
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
7620
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
5521
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...
1
4299
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
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.