我正在复制N个字节pSrc
到pDest
。这可以在一个循环中完成:
for (int i = 0; i < N; i++)
*pDest++ = *pSrc++
为什么这比memcpy
或memmove
?他们用什么技巧来加快速度?
发布于 2018-04-19 13:20:55
因为memcpy使用单词指针而不是字节指针,所以memcpy实现也经常用simd指令,这使得一次洗牌128位成为可能。
SIMD指令是可以对向量中的每个元素执行相同操作的汇编指令,长度可达16字节。这包括加载和存储指令。
发布于 2018-04-19 15:02:00
通过指针,内存复制例程可能比简单的内存复制要复杂得多,而且速度更快,例如:
void simple_memory_copy(void* dst, void* src, unsigned int bytes)
{
unsigned char* b_dst = (unsigned char*)dst;
unsigned char* b_src = (unsigned char*)src;
for (int i = 0; i < bytes; ++i)
*b_dst++ = *b_src++;
}
改进
可以做的第一个改进是对齐单词边界上的指针之一(字I指本机整数大小,通常为32位/4字节,但在较新的体系结构中可以是64位/8字节),并使用字大小的移动/复制指令。这需要使用字节对字节复制,直到指针对齐为止。
void aligned_memory_copy(void* dst, void* src, unsigned int bytes)
{
unsigned char* b_dst = (unsigned char*)dst;
unsigned char* b_src = (unsigned char*)src;
// Copy bytes to align source pointer
while ((b_src & 0x3) != 0)
{
*b_dst++ = *b_src++;
bytes--;
}
unsigned int* w_dst = (unsigned int*)b_dst;
unsigned int* w_src = (unsigned int*)b_src;
while (bytes >= 4)
{
*w_dst++ = *w_src++;
bytes -= 4;
}
// Copy trailing bytes
if (bytes > 0)
{
b_dst = (unsigned char*)w_dst;
b_src = (unsigned char*)w_src;
while (bytes > 0)
{
*b_dst++ = *b_src++;
bytes--;
}
}
}
https://stackoverflow.com/questions/-100003933
复制相似问题