我在这里对各种功能进行了测试,这就是我想出的:
write_ushort:7.81 秒
uShortToStr:8.16 秒
转换:6.71 秒
use_sprintf:49.66 秒
(Write_ushort 是我的版本,我试图尽可能清楚地写出来,而不是微优化,以格式化为给定的字符缓冲区;use_sprintf 是显而易见的 sprintf(buf, "%d", x) 什么都没有否则;其他两个取自此处的其他答案。)
这是他们之间非常惊人的区别,不是吗?谁会想到使用 sprintf 面临几乎一个数量级的差异?哦,是的,我对每个测试的函数迭代了多少次?
// Taken directly from my hacked up test, but should be clear.
// Compiled with gcc 4.4.3 and -O2. This test is interesting, but not authoritative.
int main() {
using namespace std;
char buf[100];
#define G2(NAME,STMT) \
{ \
clock_t begin = clock(); \
for (int count = 0; count < 3000; ++count) { \
for (unsigned x = 0; x <= USHRT_MAX; ++x) { \
NAME(x, buf, sizeof buf); \
} \
} \
clock_t end = clock(); \
STMT \
}
#define G(NAME) G2(NAME,) G2(NAME,cout << #NAME ": " << double(end - begin) / CLOCKS_PER_SEC << " s\n";)
G(write_ushort)
G(uShortToStr)
G(convert)
G(use_sprintf)
#undef G
#undef G2
return 0;
}
Sprintf 转换了整个可能范围的未签名短裤,然后在我大约 5 年使用的笔记本电脑上以平均每次转换大约 0.25 µs 的速度再次完成整个范围 2,999 次。
Sprintf 是可移植的;它是否也足以满足您的要求?
我的版本:
// Returns number of non-null bytes written, or would be written.
// If ret is null, does not write anything; otherwise retlen is the length of
// ret, and must include space for the number plus a terminating null.
int write_ushort(unsigned short x, char *ret, int retlen) {
assert(!ret || retlen >= 1);
char s[uint_width_10<USHRT_MAX>::value]; // easy implementation agnosticism
char *n = s;
if (x == 0) {
*n++ = '0';
}
else while (x != 0) {
*n++ = '0' + x % 10;
x /= 10;
}
int const digits = n - s;
if (ret) {
// not needed by checking retlen and only writing to available space
//assert(retlen >= digits + 1);
while (--retlen && n != s) {
*ret++ = *--n;
}
*ret = '\0';
}
return digits;
}
编译时日志 TMP 函数并不是什么新鲜事,但包括这个完整的示例,因为它是我使用的:
template<unsigned N>
struct uint_width_10_nonzero {
enum { value = uint_width_10_nonzero<N/10>::value + 1 };
};
template<>
struct uint_width_10_nonzero<0> {
enum { value = 0 };
};
template<unsigned N>
struct uint_width_10 {
enum { value = uint_width_10_nonzero<N>::value };
};
template<>
struct uint_width_10<0> {
enum { value = 1 };
};