pythonvba哪个快_Python循环⽐ExcelVBA慢?
我在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, x, "Your title", 1)
python和vb的代码可以通用吗
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下运⾏它.
此时,是命令⾏并且Excel是GUI并不重要. VM运⾏您的代码,它在您的计算机内部⽣活得更深⼀些.性能取决于已编译代码中的特定指令,以及VM运⾏这些指令的效率.在这种情况下,VB VM运⾏其P-Code的速度⽐Python VM运⾏其.pyc的速度快.
标签:python,excel,excel-vba,vba

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。