473,598 Members | 3,409 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting strings to numbers - a question of speed

I have an extremely cpu/data intensive piece of code that makes heavy
use of the following function:

void convertToDouble (const std::string& in, double& out)
{
out = atof(in.c_str() );
}

I would really like to get away from using any old C-style functions.
So, I modified the above function to make it follow the C++ convention:

void convertToDouble (const std::string& in, double& out)
{
std::stringstre am ss(in);
ss >> out;
}

However, my test code that previously took 30s to run, now takes 45s
(linux gcc 4.0.2 with -03 option). That's a heavy price to pay for
adopting the C++ convention. So, my question is... Is there an
*efficient* way to convert a string to a number (e.g. double) without
requiring the use of old C libraries?

Nov 22 '05 #1
30 3846
zexpe wrote:
I have an extremely cpu/data intensive piece of code that makes heavy
use of the following function:

void convertToDouble (const std::string& in, double& out)
{
out = atof(in.c_str() );
}

I would really like to get away from using any old C-style functions.
So, I modified the above function to make it follow the C++ convention:

void convertToDouble (const std::string& in, double& out)
{
std::stringstre am ss(in);
ss >> out;
}

However, my test code that previously took 30s to run, now takes 45s
(linux gcc 4.0.2 with -03 option). That's a heavy price to pay for
adopting the C++ convention. So, my question is... Is there an
*efficient* way to convert a string to a number (e.g. double) without
requiring the use of old C libraries?


C is legal C++ (mostly). If the C version works better, why not use it?
C libraries aren't old, they're part of modern C++.

john
Nov 22 '05 #2
zexpe wrote:
I have an extremely cpu/data intensive piece of code that makes heavy
use of the following function:

void convertToDouble (const std::string& in, double& out)
{
out = atof(in.c_str() );
}

I would really like to get away from using any old C-style functions.
So, I modified the above function to make it follow the C++ convention:

void convertToDouble (const std::string& in, double& out)
{
std::stringstre am ss(in);
ss >> out;
}

However, my test code that previously took 30s to run, now takes 45s
(linux gcc 4.0.2 with -03 option). That's a heavy price to pay for
adopting the C++ convention. So, my question is... Is there an
*efficient* way to convert a string to a number (e.g. double) without
requiring the use of old C libraries?


Hey, you could roll your own. <evil grin>

But seriously, what was the objection to using atof()? It's part of the
language for a reason. stringstream does plenty of stuff other than
just what atof does, so you get to pay for the overhead.

Also, you might be able to speed up some stuff about your stringstream
use, depending on exactly what your compiler is doing. For example,
what about making your variable ss static? You might check a few
examples of ways of doing that. Maybe the ctor call for strinstream is
where a lot of the extra time is going. But measure it before you
decide.
You also need to be more aware of initializing it as required on each
call instead of depending on the ctor to prepare it for you.
Socks

Nov 22 '05 #3

John Harrison wrote:
zexpe wrote:


<snip code comparing atof and stringstream>
However, my test code that previously took 30s to run, now takes 45s
(linux gcc 4.0.2 with -03 option). That's a heavy price to pay for
adopting the C++ convention. So, my question is... Is there an
*efficient* way to convert a string to a number (e.g. double) without
requiring the use of old C libraries?


C is legal C++ (mostly). If the C version works better, why not use it?
C libraries aren't old, they're part of modern C++.


I may be wrong, but doesn't atof suffer from the same problem as atoi -
namely that it's impossible to distinguish correctly converting zero
from an error case. I believe strtod would be a better C library
solution.

Gavin Deane

Nov 22 '05 #4
A more efficient approach using the same approach you have can be found
here:
http://www.parashift.com/c++-faq-lit....html#faq-39.2

Nov 22 '05 #5

Puppet_Sock wrote:
zexpe wrote:
I have an extremely cpu/data intensive piece of code that makes heavy
use of the following function:

void convertToDouble (const std::string& in, double& out)
{
out = atof(in.c_str() );
}

I would really like to get away from using any old C-style functions.
So, I modified the above function to make it follow the C++ convention:

void convertToDouble (const std::string& in, double& out)
{
std::stringstre am ss(in);
ss >> out;
}

However, my test code that previously took 30s to run, now takes 45s
(linux gcc 4.0.2 with -03 option). That's a heavy price to pay for
adopting the C++ convention. So, my question is... Is there an
*efficient* way to convert a string to a number (e.g. double) without
requiring the use of old C libraries?


Hey, you could roll your own. <evil grin>

But seriously, what was the objection to using atof()? It's part of the
language for a reason. stringstream does plenty of stuff other than
just what atof does, so you get to pay for the overhead.


atof() has been "deprecated " which means that it is on the way out of
the standard and should not be used in new code. It is also neither
thread-safe nor async canceable on most systems.

strtod() is the recommended replacement. Instead of calling atof like
this

#include <cstdlib>
char * nptr; // pointer to string of the number
...

double num = std::atof(nptr) ;

just replace it with a call to strtod():

double num = std::strtod(npt r, NULL);

Greg

Nov 22 '05 #6
wi******@hotmai l.com wrote:
A more efficient approach using the same approach you have can be found
here:
http://www.parashift.com/c++-faq-lit....html#faq-39.2


Is that not the same solution?

How does it differ/improve the efficiency of the conversation?

Nov 22 '05 #7
Puppet_Sock wrote:
Also, you might be able to speed up some stuff about your stringstream
use, depending on exactly what your compiler is doing. For example,
what about making your variable ss static? You might check a few
examples of ways of doing that. Maybe the ctor call for strinstream is
where a lot of the extra time is going. But measure it before you
decide.
You also need to be more aware of initializing it as required on each
call instead of depending on the ctor to prepare it for you.


Yep. If ss were static, you'd need to clear the stream each time. Can't
see it helping.

Thanks,
Ross

Nov 22 '05 #8
Greg wrote:
just replace it with a call to strtod():

double num = std::strtod(npt r, NULL);


Thanks for the tip. I'll give it a go.

My main objection to the C-way, is having to use the old <cstdlib>
library, when I'm beginning to view C++ as a complete replacement for
C. I'd rather work with C++ objects, e.g. strings, and never have to
worry about pointers, char strings etc. forever more! However, I'm
beginning to see that C++ alternatives are not always as fast as the
original C versions!

Ross

Nov 22 '05 #9
Well - it uses std::istringstr eam (specialised for reading) and the
function is inline, although I didn't do myself a measurement these two
differences are supposed to increase performance. But the stringstream
approach will give an overhead comparted to using a function like
mentioned on the other posts

Nov 22 '05 #10

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

Similar topics

8
5383
by: fo | last post by:
Does anyone know if there is a free code available to convert numbers to text and/or text to numbers? Thanks
7
2958
by: Klaus Neuner | last post by:
Hello, I need a function that converts a list into a set of regexes. Like so: string_list = print string_list2regexes(string_list) This should return something like:
5
2204
by: nickisme | last post by:
Hi - sorry for the possibly stupid question, but I'm still a wee starter on c++... Just wondering if there's a quick way to convert data into binary strings... To explain, I'm trying to convert numbers into 16 bit binary form, so that I can eventually alter the LSB for dithering purposes. Obviously I can create my own function that will do this, but I was wondering if there was some quick process that I could call up from a library that...
7
4589
by: Paul K | last post by:
I'm writing a small component that needs to be as fast as possible. The component needs to convert a string to decimal during the course of it's processing. However, I need to test the string first to make sure it is numeric. Using the is keyword doesn't work (strings cannot be cast as decimal so false is always returned) and catching an exception from Convert.ToDecimal or decimal.Parse is too slow. Does anyone know of any methods...
3
1730
by: Max Gattringer | last post by:
I have written a little programm, which converts normal Text into Unicode Bytes - nothing special, but i tried to creat 2nd Encoder which converts strings(numbers) in a textBox (strings which i had converted from UnicodeString to Bytes) to a UnicodeString. <textbox Text : 0770> ->>> byte <--- I want the numbers in the Array ---->>>> as UnicodeString: M Thx PS: Please ignore the broken English - It's hard to discribe my problem..
2
3996
by: CoreyWhite | last post by:
Problem: You have numbers in string format, but you need to convert them to a numeric type, such as an int or float. Solution: You can do this with the standard library functions. The functions strtol, strtod, and strtoul, defined in <cstdlib>, convert a null- terminated character string to a long int, double, or unsigned long. You can use them to convert numeric strings of any base to a numeric
21
1995
by: py_genetic | last post by:
Hello, I'm importing large text files of data using csv. I would like to add some more auto sensing abilities. I'm considing sampling the data file and doing some fuzzy logic scoring on the attributes (colls in a data base/ csv file, eg. height weight income etc.) to determine the most efficient 'type' to convert the attribute coll into for further processing and efficient storage... Example row from sampled file data: , ....]
4
1814
by: josha13 | last post by:
I am very new to C++ and I am trying to figure out how to convert a number to a string (even in the simplest case such as #include <iostream> #include <sstream> using namespace std; int main () { int a; a = 1; b = 2;
16
4124
by: luca bertini | last post by:
Hi, i have strings which look like money values (ie 34.45) is there a way to convert them into float variables? everytime i try I get this error: "numb = float(my_line) ValueError: empty string for float()" " here's the code ************
0
7991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7902
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
8395
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
8398
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
5438
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
3898
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
3939
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2412
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
1
1504
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.