Re: how could "atof" be so slow in vc2005?
"Barry Schwarz" <schwarzb@doezl.net> wrote in message
news:psurd31o8072lr63e40e5t50fmcbrdihne@4ax.com...
On Tue, 04 Sep 2007 07:00:04 -0000, Leo Jay <Python.LeoJay@gmail.com>
wrote:
i'm using visual studio 2005, and compile the code in release mode
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <math.h>
using namespace std;
int main()
{
int i = 0;
double sum = 0.0;
clock_t start = clock();
for (i=0; i<10000000; i++)
{
sum += atof("1.123400e01");
}
cout << "time: " << double(clock() - start) / CLOCKS_PER_SEC <<
"\tresult: " << sum << endl;
return 0;
}
the code runs more than 7.0 seconds on my Intel Xeon 3.0 box.
meanwhile, the same code runs less than 2.0 seconds on a AMD Athlon
2000+ box which runs freebsd 6.1 and gcc 3.4.4
Since you didn't include stdlib.h, there is no prototype in scope for
atof. The compiler therefore assumes that atof returns an int. Since
that is not true, you have undefined behavior. (And probably a fair
amount of code to convert the non-existent int to a double.) Why not
run it with a loop limit of 5 and work out the bugs first?
Don't quite qet what you mean here. If it didn't know the prototype,
how would it know what the function did?
He's not including cstdlib directly as he should
but iostream is pulling in istream which is including
ostream which is including ios which is
including xlocnum which is including cstdlib.
On my P4 3.0 using VC++ 2005 express with optimized for
speed, this takes 6.59 seconds. Oddly enough, running
the same code on Borland's Turbo Explorer, it's around
3 seconds. And even more oddly, if I change the string
to "1.0" it runs on VC in around 3 seconds.
This is the code that I used:
#include <iostream>
#include <ctime>
#include <cstdlib>
int main(){
double sum = 0.0;
clock_t start = clock();
for (int i=0; i<10000000; ++i)
sum += std::atof("1.123400e01");
std::cout << "time: " << double(clock() - start) / CLOCKS_PER_SEC <<
"\tresult: " << sum << std::endl;
return 0;
}
I haven't used atof() in quite a while so I thought
I'd try it in something I'm more likely to use.
Happily, this code runs in about 3 seconds as well:
#include <iostream>
#include <ctime>
#include <sstream>
int main(){
double sum = 0.0;
clock_t start = clock();
double f;
std::stringstream ss;
for (int i=0; i<10000000; ++i){
ss << "1.123400e01";
ss >> f;
sum += f;
}
std::cout << "time: " << double(clock() - start) / CLOCKS_PER_SEC <<
"\tresult: " << sum << std::endl;
return 0;
}