gpt4 book ai didi

function - 有或没有类型注释会发生特化吗?

转载 作者:行者123 更新时间:2023-12-05 05:38:57 24 4
gpt4 key购买 nike

Documentation :

Argument-type declarations normally have no impact on performance:regardless of what argument types (if any) are declared, Juliacompiles a specialized version of the function for the actual argumenttypes passed by the caller. For example, calling fib(1) will triggerthe compilation of specialized version of fib optimized specificallyfor Int arguments, which is then re-used if fib(7) or fib(15) arecalled.

提供的示例:

fib(n::Integer) = n ≤ 2 ? one(n) : fib(n-1) + fib(n-2)

然后在 Performance Tips :

# This will not specialize:

function f_type(t) # or t::Type
x = ones(t, 10)
return sum(map(sin, x))
end

根据我对性能提示的理解,有或没有类型注释 fib(b::Integer)fib(b) shouldn't specialize 专门用于 Int 参数。

似乎有或没有类型注释都不会发生特化,但为什么手册似乎表明它会特化?

最佳答案

性能提示页面中的示例是关于将类型本身 作为参数传递给函数的特定情况。正如该部分的开头所说:

Julia avoids automatically specializing on argument type parameters in three specific cases: Type, Function, and Vararg

f_type 在该示例中是一个接受 Type t 的函数。例如,对该函数的调用类似于 f_type(Int)。该部分说在这种情况下,类型特化不是基于 Int 类型完成的,其中 Int 作为参数本身的值传递(然后通过到另一个函数)。 (具体来说,Type 并未专用于特定的参数化类型,如 Type{Int},如果参数不是上述之一,通常情况下三种情况。)

这不适用于 fib 方法(或我们通常定义的大多数方法)。 fib 接受类型为(子类型)Integer,而不是类型本身。在这种情况下,像 fib(1)fib(UInt8(2)) 这样的调用确实会创建函数的类型专用编译版本。

关于function - 有或没有类型注释会发生特化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72805972/

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