gpt4 book ai didi

c - 了解 memcpy() 的源代码

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

00018 void *memcpy(void *dst, const void *src, size_t len)
00019 {
00020 size_t i;
00021
00022 /*
00023 * memcpy does not support overlapping buffers, so always do it
00024 * forwards. (Don't change this without adjusting memmove.)
00025 *
00026 * For speedy copying, optimize the common case where both pointers
00027 * and the length are word-aligned, and copy word-at-a-time instead
00028 * of byte-at-a-time. Otherwise, copy by bytes.
00029 *
00030 * The alignment logic below should be portable. We rely on
00031 * the compiler to be reasonably intelligent about optimizing
00032 * the divides and modulos out. Fortunately, it is.
00033 */
00034
00035 if ((uintptr_t)dst % sizeof(long) == 0 &&
00036 (uintptr_t)src % sizeof(long) == 0 &&
00037 len % sizeof(long) == 0) {
00038
00039 long *d = dst;
00040 const long *s = src;
00041
00042 for (i=0; i<len/sizeof(long); i++) {
00043 d[i] = s[i];
00044 }
00045 }
00046 else {
00047 char *d = dst;
00048 const char *s = src;
00049
00050 for (i=0; i<len; i++) {
00051 d[i] = s[i];
00052 }
00053 }
00054
00055 return dst;
00056 }

我刚刚经历了 memcpy 的实现, 了解它与使用循环有何不同。但是我看不出使用循环而不是 memcpy 有什么区别。 , 作为 memcpy在内部再次使用循环进行复制。

我听不懂if他们为整数所做的部分 — i < len/sizeof(long) .为什么需要这个计算?

最佳答案

I couldn't understand if part they do for integers. i < len/sizeof(long). Why is this calculation required ?

因为在这种情况下它们复制的是单词,而不是单个字节(正如评论所说,这是一种优化 - 它需要更少的迭代,CPU 可以更有效地处理单词对齐的数据)。

len 是要复制的字节数sizeof(long)单个单词的大小,因此要复制的元素数(即要执行的循环迭代)为 len/sizeof(long)

关于c - 了解 memcpy() 的源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17591624/

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