Anyway, I wrote a macro to do the same thing as atoi and did a performance test.
Code:
Results:
#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;
}
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:
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.
Post a Comment