Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any alternative to strtoull() function in C?

I need to convert char* to unsigned long long int and there is a function called strtoull() in the C standard library but it takes to much time. I need to quick conversion between char* to unsigned long long int. How can I write my own conversion function which is faster than the standard one?


1 Answers

Shortest/fastest code I can think of right now:

unsigned long long strtoull_simple(const char *s) {
  unsigned long long sum = 0;
  while (*s) {
    sum = sum*10 + (*s++ - '0');
  }
  return sum;
}

No error checking. Profile to find if it improves performance. YMMV.


After accept: Tried a variation that does the initial calculation as unsigned before continuing on to unsigned long long. Marginal to negative improvements on my 64-bit machine depending on number set. Suspect it will be faster on machines where unsigned long long operations are expensive.

unsigned long long strtoull_simple2(const char *s) {
  unsigned sumu = 0;
  while (*s) {
    sumu = sumu*10 + (*s++ - '0');
    if (sumu >= (UINT_MAX-10)/10) break;  // Break if next loop may overflow
  }
  unsigned long long sum = sumu;
  while (*s) {
    sum = sum*10 + (*s++ - '0');
  }
  return sum;
}

If code knows the length of the string then the following had some performance improvements (5%)

unsigned long long strtoull_2d(const char *s, unsigned len) {
  unsigned sumu = 0;
  #define INT_MAX_POWER_10 9
  if (len > INT_MAX_POWER_10) {
    len = INT_MAX_POWER_10;
  }
  while (len--) {
    sumu = sumu * 10 + (*s++ - '0');
  }
  unsigned long long sum = sumu;
  while (*s) {
    sum = sum * 10 + (*s++ - '0');
  }
  return sum;
}

Conclusion: Improvements (I tried 7) on the simple original solution could yield small incremental speed efficiencies, but they become more and more platform and data set dependent. Suggest that programing talent is better applied to the higher level code improvements.

like image 192
chux - Reinstate Monica Avatar answered Oct 18 '25 08:10

chux - Reinstate Monica