小编Til*_*ill的帖子

对于通过的函数的评估比在朱莉亚中的直接评估慢.有解决方法吗?

假设我有许多不同的非常简单的函数,称为f1,f2,....我想将所有f函数存储在fStruct中,并将其中一个f函数传递给例如g,当我在我的代码中需要它时.但是当我将函数f传递给g时,函数g()的求值要慢得多.有解决方法吗?我丑陋的解决方案是使用一个整体函数,它通过if-else语句选择正确的f()函数.下面是慢速计算的最小示例.

using BenchmarkTools
struct fFunction
    f1
    f2
end
f() = return 1
fStruct = fFunction(f, f)
g = fStruct.f1
@btime f() --> 0.001 ns (0 allocations: 0 bytes)
@btime g() --> 9.591 ns (0 allocations: 0 bytes)
Run Code Online (Sandbox Code Playgroud)

EDIT1:

我还可以问一下,为什么函数g比较慢,或者如何在下面的最小例子中使它像f一样快

using BenchmarkTools
f() = return 1
func = "f"
g = eval(Meta.parse(func))
f == g -->true
@btime f() --> 0.001 ns (0 allocations: 0 bytes)
@btime g() --> 11.907 ns (0 allocations: 0 bytes)
Run Code Online (Sandbox Code Playgroud)

EDIT2:

谢谢您的回答.我用解决方案更新帖子.

using BenchmarkTools
f() = return …
Run Code Online (Sandbox Code Playgroud)

julia

4
推荐指数
1
解决办法
106
查看次数

一个宏总是比julia中的函数更快吗?

我有兴趣传递一个简单函数的值(在下面的最小例子中为2).我的最小例子表明宏比函数快得多.这是对的还是我犯了错误?

using BenchmarkTools
macro func!(arg)
    arg = eval(arg)
    for i in 1:length(arg)
        arg[i] = 2
    end
    return nothing
end
function func!(arg)
    for i in 1:length(arg)
        arg[i] = 2
    end
    return nothing
end
x = ones(10^3)
@btime @func!(x) --> 0.001 ns (0 allocations: 0 bytes)
@btime func!(x) --> 332.272 ns (0 allocations: 0 bytes)
Run Code Online (Sandbox Code Playgroud)

EDIT1:

不,它不快.似乎@btime和@time宏不适用于宏.我在下面的最小例子中用@time宏检查了它.我计算了宏的秒数,即使@time告诉我几乎没有时间.

x = ones(10^7)
@time @func!(x) --> 0.000001 seconds (3 allocations: 144 bytes)
@time func!(x) --> 0.007362 seconds (4 allocations: 160 bytes)
Run Code Online (Sandbox Code Playgroud)

julia

0
推荐指数
1
解决办法
99
查看次数

标签 统计

julia ×2