gpt4 book ai didi

c++ - 如何消除对幂等函数的额外调用?

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

有没有办法告诉 gcc 如果两个后续调用具有相同的参数,则只应调用具有副作用的函数一次。我想要以下行为:

foo(6);//run this function
foo(6);//optimize this away
foo(6);//optimize this away
foo(5);//run this function
foo(6);//run this function again

我可以让 foo 在它做任何工作之前检查一个全局变量,但这不是最优的。

void inline foo(int i){
static int last_i=i+1;
if(last_i != i){
last_i==i;
//do_work...
}
}

由于 foo 是一个内联函数,编译器应该能够查看对 foo() 的调用,并确定它不必执行它。问题是编译器无法针对全局变量进行优化,有没有办法让编译器知道这样做是安全的?

最佳答案

... a function that has side effects should only be called once if two subsequent calls have the same arguments...

尽管它有副作用,但该函数必须是幂等的。

C++ 标准只区分有副作用(I/O 函数)和没有副作用的函数。从编译器的角度来看,如果函数是不透明的(在同一个翻译单元中没有定义),那么它一定有副作用,因此它是一个编译器内存屏障,编译器无法优化调用或推断返回值(除非它是编译器内部函数,如 memcpy)。

Idempotence, computer science meaning :

In computer science, the term idempotent is used more comprehensively to describe an operation that will produce the same results if executed once or multiple times.[4] This may have a different meaning depending on the context in which it is applied. In the case of methods or subroutine calls with side effects, for instance, it means that the modified state remains the same after the first call. In functional programming, though, an idempotent function is one that has the property f(f(x)) = f(x) for any value x.[5]

C++ 没有这个概念。

关于c++ - 如何消除对幂等函数的额外调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25455660/

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