I have this code:
void
fill_array (unsigned int *iarray, char *string, int max)
{
int ipos = 0;
char *iholder;
iholder = strtok (string, ",");
while (iholder != NULL)
{
iarray[ipos++] = atoi (iholder);
if (ipos == max)
{
return;
}
iholder = strtok (NULL, ",");
}
}
It takes a string “1,2,3,4” for example, and enters the numbers into an array.
I put this in a loop and got 3.3 seconds runtime.
With this code:
void
fill_array (unsigned int *iarray, char *string, int max)
{
int ipos = 0;
char *iholder;
if (!strchr (string, ','))
{
iarray[0] = atoi (string);
return;
}
iholder = strtok (string, ",");
while (iholder != NULL)
{
iarray[ipos++] = atoi (iholder);
if (ipos == max)
{
return;
}
iholder = strtok (NULL, ",");
}
}
It took about 1.4 seconds to execute.
The only difference is the strchr which I inserted just to see if it would run faster on single numbers, but it runs much faster on longer lists for some reason.
Can anyone explain why?
I am testing with this code:
int main ()
{
unsigned int iarray[5];
char str_test[] = "56,75,22,83";
int i;
struct timeval start;
struct timeval end;
gettimeofday (&start, NULL);
for (i = 0; i < 10000000; i++)
{
fill_array (iarray, str_test, 5);
}
gettimeofday (&end, NULL);
if (end.tv_usec - start.tv_usec < 0)
{
end.tv_usec += 1000000L;
end.tv_sec -= 1;
}
printf ("Runtime: %ld s %03ld ms\n",
end.tv_sec - start.tv_sec, (end.tv_usec - start.tv_usec) / 1000);
return 0;
}
Presumably that first strchr is making your code drop out earlier so that it doesn’t have to do as much processing?