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

独自空忆成欢 提交于 2019-12-23 17:13:52

问题


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:


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.




回答2:


Answer from @soerium modified to use unsigned long long give better performance than strtoull().

unsigned long long  fast_atoull(const char *str)
{
    unsigned long long val = 0;
    while(*str)
    {
        val = (val << 1) + (val << 3) + (*(str++) - 48);
    }
    return val;
}


来源:https://stackoverflow.com/questions/33320876/is-there-any-alternative-to-strtoull-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!