To answer the second part of your question, for me, it appears that atoi
is about twice as fast. Consider the following:
#define ITERS 1000000
clock_t testAtoi()
{
char buffer[64];
clock_t start = clock();
for (int i = 0; i < ITERS; i++) {
sprintf(buffer, "%i", i);
int l = atoi(buffer);
}
return clock() - start;
}
clock_t testScanf()
{
char buffer[64];
clock_t start = clock();
for (int i = 0; i < ITERS; i++) {
sprintf(buffer, "%i", i);
int l = 0;
sscanf(buffer, "%i", &l);
}
return clock() - start;
}
int main()
{
printf("clocks for atoi: %lu\n", testAtoi());
printf("clocks for sscanf: %lu\n", testScanf());
return 0;
}
For me, using gcc and -O0
(so my variables aren't optimized away), the program outputs:
clocks for atoi: 222011
clocks for sscanf: 392409
But, if you are using a FILE *
, then maybe fscanf
would be faster. I don't have the time to compare the two right now, but for raw strings, I would just use atoi
for the most part.