是否有任何替代strtoull将()函数在C中?函数、有任何、strtoull

由网友(不见面,好像剩似简单)分享简介:我要的char * 转换为无符号长long int类型键,有一个叫 strtoull将()在 C 标准库,但它需要很多时间。我需要的char * 之间的快速转换,以无符号长long int类型。我怎么能写我自己的转换函数,它比标准的速度更快?I need to convert char* to unsigned lo...

我要的char * 转换为无符号长long int类型键,有一个叫 strtoull将()在 C 标准库,但它需要很多时间。我需要的char * 之间的快速转换,以无符号长long int类型。我怎么能写我自己的转换函数,它比标准的速度更快?

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?

推荐答案

最短/最快的code我能想到的现在:

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.

在接受:试过,做初步计算为无符号的变化继续到前无符号长长。边际为根据一些设置在我的64位计算机负的改善。怀疑这将是更快的机器,其中无符号长长操作是昂贵的。

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;
}

如果code知道字符串的长度,那么下面有一些性能改进(5%)

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;
}

结论:改进(我试图7)上的简单的原溶液可产生小的增量速度效率,但它们变得越来越平台及数据集相关。建议编程人才是更好地应用于上级code改进。

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.

阅读全文

相关推荐

最新文章