{C++ etc.}

Latest Posts
 
Home | C++ Posts | Linux Posts | Programming Posts | Issue Tracking Posts

Thursday, April 17, 2008

atoi vs. Custom String to Int Convertion

I had two code reviews of my process and it turned up a plethora of bugs and unoptimized code. One of these was a function which is called very frequently, which contained three atoi calls. atoi is expensive, I know, but I didn't have an idea as to HOW expensive it was. Further, I thought there was no other way to achieve its results, until our team lead Mr. Prabath Fernando pointed out that it was possible to get the corresponding value of a ascii int character by subtracting 48 from it. This could be better understood by looking at an ascii table.

Anyway, I wrote a macro to do the same thing as atoi and did a performance test.


Code:

#include
#include
#include

#define QSaToi(iLen, zString, iOut) {int j = 1; iOut = 0; \
for (int i = iLen - 1; i >= 0; --i) \
{ iOut += ((zString[i] - 48) * j); \
j = j*10;}}

int main(int argc, char** argv)
{
clock_t ct_start = clock();
const char* zTest = "1234567";
int iOut = 0;

for (int i = 0; i < result = " << iOut << std::endl; std::cout << " time = " << ((double)clock() - ct_start)/(CLOCKS_PER_SEC) << " ct_start =" clock();" i =" 0;" iout =" atoi(zTest);" result = " << iOut << std::endl; std::cout << " time = " << ((double)clock() - ct_start)/(CLOCKS_PER_SEC) << ">> iOut;
}

Results:

Result from custom method = 1234567
Time for custom method = 0.063 us
Result from atoi = 1234567
Time for atoi = 0.422 us

Conclusion : Custom atoi macro is ~7 times faster than normal atoi.

NOTE: this was tested only with microsoft visual c++ 2008 compiler so results might differ on unix machines

1 comment:

Anonymous said...

I think it's possible that atoi preprocesses the char* to check that it contains a valid number. That's where the difference might be. Other detail, atoi manages to convert negative numbers, with string starting with '-'. That's a detail but the checking might take longer to process than we usually think.