gpt4 book ai didi

c - 在 C 中将一个结构分配给另一个结构

转载 作者:行者123 更新时间:2023-11-30 21:21:31 28 4
gpt4 key购买 nike

假设我有 2 个结构 s1s2,每个结构包含 10000 个元素的数组。如果我将一个结构复制到另一个结构,例如 s1=s2 并从 1 循环到 10000,然后 s1[i]=s2[i]。这两种方法之间会有速度差异吗?如果是,请告诉哪个更快,为什么?

最佳答案

执行摘要:

在我的编译器上,所有这些都转换为对类似函数的 memcpy() 的调用。它们恰好不同,但编译器或多或少地认识到所有这些实现在功能上都是相同的。

这些不同的 memcpy() 实现之间的性能差异可能很小。

代码:

#include <stdlib.h>
#include <string.h>

struct S {
int x[10000];
};

void impl1(struct S *x, struct S *y) __attribute__((noinline));
void impl1(struct S *x, struct S *y) {
*x = *y;
}

void impl2(struct S *x, struct S *y) __attribute__((noinline));
void impl2(struct S *x, struct S *y) {
memcpy(x, y, sizeof(*x));
}

void impl3(struct S * restrict x, struct S * restrict y) __attribute__((noinline));
void impl3(struct S * restrict x, struct S * restrict y) {
for (int i=0; i<10000; ++i)
x->x[i] = y->x[i];
}

int main() {
struct S x, y;
impl1(&x, &y);
impl2(&x, &y);
impl3(&x, &y);
}

生成的 LLVM 代码

define void @impl1(%struct.S* nocapture %x, %struct.S* nocapture readonly %y) #0 {
%1 = bitcast %struct.S* %x to i8*
%2 = bitcast %struct.S* %y to i8*
tail call void @llvm.memcpy.p0i8.p0i8.i64(i8* %1, i8* %2, i64 40000, i32 4, i1 false), !tbaa.struct !1
ret void
}

define void @impl2(%struct.S* %x, %struct.S* %y) #0 {
%1 = bitcast %struct.S* %x to i8*
%2 = bitcast %struct.S* %y to i8*
%3 = tail call i64 @llvm.objectsize.i64.p0i8(i8* %1, i1 false)
%4 = tail call i8* @__memcpy_chk(i8* %1, i8* %2, i64 40000, i64 %3) #1
ret void
}

define void @impl3(%struct.S* noalias nocapture %x, %struct.S* noalias nocapture readonly %y) #0 {
%x2 = bitcast %struct.S* %x to i8*
%y3 = bitcast %struct.S* %y to i8*
call void @llvm.memcpy.p0i8.p0i8.i64(i8* %x2, i8* %y3, i64 40000, i32 4, i1 false)
ret void
}

编译器信息

[10:04am][wlynch@watermelon /tmp] clang -v
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix

关于c - 在 C 中将一个结构分配给另一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25711237/

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