gpt4 book ai didi

julia - 为什么 Julia 运行函数的速度比非等效函数快?

转载 作者:行者123 更新时间:2023-12-01 08:29:42 26 4
gpt4 key购买 nike

所以,今天我决定尝试 Julia,但我遇到了一些奇怪的事情,我无法完全理解原因,也无法通过搜索查询找到合适的答案,所以我在这里......

首先,我想有一些东西可以用来对 Python 进行基准测试,我选择了这段非常简单的代码。

def test():            
start = time()
a = 1
while a < 10000000:
a+=1
print(time() - start)

在我的机器上用 Python 3.3 执行这需要大约 0.9 秒。然后我在 Julia 中运行了以下代码。

start = time()
a = 1
while a < 10000000
a+=1
end
print(time() - start)

执行需要 ~0.7s。所以我得出结论,Julia 中的简单算术性能对 Python 来说是 ~=。

然而,当我把它变成一个函数时,我偶然发现了一个我没有预料到的奇怪现象,这让我的结果发生了变化。

function test_arithmetic()
start = time()
a = 1
while a < 10000000
a+=1
end
print(time() - start)
end

test_arithmetic()

这个代码片段只用了 ~0.1s 来执行,这是为什么呢?

最佳答案

原因是全局变量的类型可以随时更改,这使得编译器难以优化。这在 Performance Tips section of the manual 中有所提及.

关于julia - 为什么 Julia 运行函数的速度比非等效函数快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22345175/

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