gpt4 book ai didi

c - C中一个奇怪的字符串复制函数

转载 作者:太空狗 更新时间:2023-10-29 16:53:35 25 4
gpt4 key购买 nike

当我阅读nginx代码时,我看到了这个函数:

#define ngx_cpymem(dst, src, n)   (((u_char *) memcpy(dst, src, n)) + (n))

static ngx_inline u_char *
ngx_copy(u_char *dst, u_char *src, size_t len)
{
if (len < 17) {

while (len) {
*dst++ = *src++;
len--;
}

return dst;

} else {
return ngx_cpymem(dst, src, len);
}
}

这是一个简单的字符串复制函数。但是为什么它会测试字符串的长度并在长度 >= 17 时切换到 memcpy?

最佳答案

这是一种优化 - 对于非常小的字符串,简单复制比调用系统 (libc) 复制函数更快。

使用 while 循环的简单复制对于短字符串工作得相当快,并且系统复制函数(通常)对长字符串进行了优化。但系统副本也会进行大量检查和一些设置。

其实这段代码之前有作者的注释:nginx,/src/core/ngx_string.h (搜索ngx_copy)

/*
* the simple inline cycle copies the variable length strings up to 16
* bytes faster than icc8 autodetecting _intel_fast_memcpy()
*/

此外,上面的两行是

#if ( __INTEL_COMPILER >= 800 )

因此,作者进行了测量并得出结论,ICC 优化的 memcopy 进行了长时间的 CPU 检查以选择最优化的 memcopy 变体。他发现手动复制 16 个字节比来自 ICC 的最快 memcpy 代码更快。

对于其他编译器,nginx 确实直接使用 ngx_cpymem (memcpy)

#define ngx_copy                  ngx_cpymem

作者对不同大小的不同 memcpy 进行了研究:

/*
* gcc3, msvc, and icc7 compile memcpy() to the inline "rep movs".
* gcc3 compiles memcpy(d, s, 4) to the inline "mov"es.
* icc8 compile memcpy(d, s, 4) to the inline "mov"es or XMM moves.
*/

关于c - C中一个奇怪的字符串复制函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5647350/

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