本文介绍了是否有任何替代strtoull将()函数在C中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要的char * 转换为无符号长long int类型键,有一个叫<$ C $函数C> 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.

这篇关于是否有任何替代strtoull将()函数在C中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:35