加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python循环比Excel VBA慢?

发布时间:2020-12-20 12:08:07 所属栏目:Python 来源:网络整理
导读:我在excel(VBA)和 python执行简单循环之间进行了一些测试.代码如下.令我惊讶的是,vba明显快于python.快了近6倍.我认为,由于python在命令行中运行,因此性能会更好.你们对此有何评论? Python import timeimport ctypes # An included library with Python ins
我在excel(VBA)和 python执行简单循环之间进行了一些测试.代码如下.令我惊讶的是,vba明显快于python.快了近6倍.我认为,由于python在命令行中运行,因此性能会更好.你们对此有何评论?

Python

import time
import ctypes  # An included library with Python install.
start_time = time.time()

for x in range(0,1000000):
    print x

x = ("--- %s seconds ---" % (time.time() - start_time))
ctypes.windll.user32.MessageBoxA(0,x,"Your title",1)

Excel(VBA)

Sub looptest()

Dim MyTimer As Double

MyTimer = Timer

Dim rng As Range,cell As Range
Set rng = Range("A1:A1000000")

x = 1
For Each cell In rng

    cell.Value = x
    x = x + 1
Next cell


MsgBox Timer - MyTimer
End Sub

解决方法

你的两个代码示例没有做同样的事情.在Python代码中,内部循环必须:

>询问范围内的下一个数字(0,1000000).
>显示它.

在VBA代码中,Excel必须:

>请求Range中的下一个单元格(“A1:A1000000”)(与Python范围无关).
>设置cell.Value属性.
>运行各种代码Excel只要更改单元格就会执行.
>检查是否需要重新计算任何公式.
>显示它.
>递增x.

让我们重写一下,让Python和VBA循环做同样的事情,尽可能接近:

Python

import time
import ctypes
start_time = time.time()

x = 0
while x <= 1000000:
    x = x + 1

x = ("--- %s seconds ---" % (time.time() - start_time))
ctypes.windll.user32.MessageBoxA(0,1)

VBA

Declare Function QueryPerformanceCounter Lib "kernel32" (t As Currency) As Boolean
Declare Function QueryPerformanceFrequency Lib "kernel32" (t As Currency) As Boolean

Sub looptest()
    Dim StartTime As Currency
    QueryPerformanceCounter StartTime

    x = 0
    Do While x <= 1000000
        x = x + 1
    Loop

    Dim EndTime As Currency
    QueryPerformanceCounter EndTime
    Dim Frequency As Currency
    QueryPerformanceFrequency Frequency

    MsgBox Format$((EndTime - StartTime) / Frequency,"0.000")
End Sub

在我的计算机上,Python需要大约96毫秒,而VBA 33毫秒 – VBA的执行速度要快三倍.如果你投入Dim x As Long,它的速度会提高六倍.

为什么?那么,让我们来看看每个如何运行. Python在内部将.py文件编译为.pyc,并在Python VM下运行它. Another answer describes the Python case in detail. Excel将VBA编译为MS P-Code,并在Visual Basic VM下运行它.

此时,python.exe是命令行并且Excel是GUI并不重要. VM运行您的代码,它在您的计算机内部生活得更深一些.性能取决于已编译代码中的特定指令,以及VM运行这些指令的效率.在这种情况下,VB VM运行其P-Code的速度比Python VM运行其.pyc的速度快.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读