gpt4 book ai didi

c++ - char[] 到十六进制字符串练习

转载 作者:可可西里 更新时间:2023-11-01 18:42:10 24 4
gpt4 key购买 nike

下面是我当前的 char* 到十六进制字符串函数。我把它写成位操作练习。在 AMD Athlon MP 2800+ 上十六进制化一个 1000 万字节的数组需要大约 7 毫秒。我缺少任何技巧或其他方法吗?

我怎样才能让它更快?

在 g++ 中使用 -O3 编译

static const char _hex2asciiU_value[256][2] =
{ {'0','0'}, {'0','1'}, /* snip..., */ {'F','E'},{'F','F'} };

std::string char_to_hex( const unsigned char* _pArray, unsigned int _len )
{
std::string str;
str.resize(_len*2);
char* pszHex = &str[0];
const unsigned char* pEnd = _pArray + _len;

clock_t stick, etick;
stick = clock();
for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) {
pszHex[0] = _hex2asciiU_value[*pChar][0];
pszHex[1] = _hex2asciiU_value[*pChar][1];
}
etick = clock();

std::cout << "ticks to hexify " << etick - stick << std::endl;

return str;
}

更新

添加了时间代码

Brian R. Bondy :用堆分配的缓冲区替换 std::string 并将 ofs*16 更改为 ofs << 4 - 但是堆分配的缓冲区似乎减慢了速度? - 结果 ~11ms

Antti Sykäri : 将内循环替换为

 int upper = *pChar >> 4;
int lower = *pChar & 0x0f;
pszHex[0] = pHex[upper];
pszHex[1] = pHex[lower];

结果~8ms

Robert : 将 _hex2asciiU_value 替换为完整的 256 条目表,牺牲了内存空间但结果为 ~7ms!

HoyHoy : 注意到它产生了不正确的结果

最佳答案

这个汇编函数(基于我之前在这里的帖子,但我必须稍微修改一下概念才能让它实际工作)在 Core 2 的一个内核上每秒处理 33 亿个输入字符(66 亿个输出字符)康罗 3Ghz。 Penryn 可能更快。

%include "x86inc.asm"

SECTION_RODATA
pb_f0: times 16 db 0xf0
pb_0f: times 16 db 0x0f
pb_hex: db 48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70

SECTION .text

; int convert_string_to_hex( char *input, char *output, int len )

cglobal _convert_string_to_hex,3,3
movdqa xmm6, [pb_f0 GLOBAL]
movdqa xmm7, [pb_0f GLOBAL]
.loop:
movdqa xmm5, [pb_hex GLOBAL]
movdqa xmm4, [pb_hex GLOBAL]
movq xmm0, [r0+r2-8]
movq xmm2, [r0+r2-16]
movq xmm1, xmm0
movq xmm3, xmm2
pand xmm0, xmm6 ;high bits
pand xmm2, xmm6
psrlq xmm0, 4
psrlq xmm2, 4
pand xmm1, xmm7 ;low bits
pand xmm3, xmm7
punpcklbw xmm0, xmm1
punpcklbw xmm2, xmm3
pshufb xmm4, xmm0
pshufb xmm5, xmm2
movdqa [r1+r2*2-16], xmm4
movdqa [r1+r2*2-32], xmm5
sub r2, 16
jg .loop
REP_RET

请注意,它使用 x264 汇编语法,这使其更具可移植性(32 位与 64 位等)。将其转换为您选择的语法很简单:r0、r1、r2 是寄存器中函数的三个参数。它有点像伪代码。或者您可以从 x264 树中获取 common/x86/x86inc.asm 并包含它以在 native 运行它。

附言Stack Overflow,我在这种微不足道的事情上浪费时间是不是错了?或者这很棒吗?

关于c++ - char[] 到十六进制字符串练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com