gpt4 book ai didi

python - 为什么这个算法在 Python 中比它的 VB.net 实现慢?

转载 作者:太空宇宙 更新时间:2023-11-03 13:45:10 25 4
gpt4 key购买 nike

以下代码在 Python 3.3 上运行大约需要两分钟,但等效的 VB.net 版本运行时间不到一秒。我在这里做的是否特别低效导致它在 Python 上变慢?或者它只是一个较慢的解释器? Python 的数学库能慢那么多吗? (将 x、x1 和 x3 初始化为 float 并没有太大区别)。

inc = 2*3*5*7
for x in range(inc,200000,inc):
n = 0
y = x * x + x

for x1 in range(x+1, y):
x2 = x1 / (x1 - x) * x
x3 = round(x2)
if abs(x2 - x3) < 0.0000001:
if x3 < x1: break
n += 1
if n > 500: print(x, n)

(我意识到有更好的算法可以完成同样的事情。我有兴趣改进它的 Python 实现,以便学习更多 Python。)

VB代码:

Dim x, x1, x2, x3, y As Double
Dim n As Integer

For x = 0 To 200000 Step 2 * 3 * 5 * 7
n = 0
y = x * x + x
For x1 = x + 1 To y
x2 = x1 / (x1 - x) * x
x3 = Round(x2)
If Math.Abs(x2 - x3) < 0.0000001 Then
If x3 < x1 Then Exit For
n += 1
End If
Next x1
If n > 500 Then sb.Append(x & " " & x1 & " " & x3 & " " & n & vbCrLf)
Next x

最佳答案

你没有写过特别低效的代码,没有。您只是看到纯解释语言(而且不是特别快的语言)和编译语言之间的正常性能差异。作为证据,请考虑通过在 cProfile 下运行您的代码十五秒生成的配置文件:

% python3 -m cProfile stackoverflow.py & pid=$\!; sleep 15; kill -INT $!
55440 608
60060 608
65520 608
69300 563
73920 527
78540 608
32855602 function calls in 14.969 seconds
Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)
1 10.557 10.557 14.969 14.969 so.py:1(<module>)
16427796 0.646 0.000 0.646 0.000 {built-in method abs}
1 0.000 0.000 14.969 14.969 {built-in method exec}
6 0.000 0.000 0.000 0.000 {built-in method print}
16427797 3.766 0.000 3.766 0.000 {built-in method round}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

您最大的成本中心似乎是 round 函数,但即便如此也只消耗大约三分之一的运行时间。这表明问题不是您自己代码的任何特定部分,而是低效算法和缓慢解释器的组合。

关于python - 为什么这个算法在 Python 中比它的 VB.net 实现慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21763434/

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