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 the string "1,2,3,4", for example, and enters the numbers into an array. I put this in a loop and got a run time of 3.3 seconds.
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 complete.
The only difference is strchr, which I inserted to see if it will work faster on single numbers, but for some reason it works much faster on longer lists.
Can someone explain why?
I am testing 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; }