1

我正在尝试测量读取然后加密一些数据(独立)需要多长时间。但我似乎无法在 timeit 内访问预先创建的数据 obj(因为它在自己的虚拟环境中运行)

这工作正常(定时文件读取操作):

t = timeit.Timer("""
openFile = open('mytestfile.bmp', "rb")
fileData = openFile.readlines()    
openFile.close()""")
readResult = t.repeat(1,1)
print ("\Finished reading in file")

以下不起作用,因为我无法访问'fileData' obj。我不能从 timeit 函数内部再次创建它,否则会增加整体执行时间。

定时加密操作:

tt = timeit.Timer("""
from Crypto.Cipher import AES
import os
newFile = []
key = os.urandom(32)
cipher = AES.new(key, AES.MODE_CFB)
for lines in fileData:
newFile = cipher.encrypt(lines)""")
encryptResult = tt.repeat(1,1)
4

2 回答 2

1

timeit需要一个只运行一次的设置参数

来自文档:

设置:最初执行一次的语句(默认“通过”)

例如:

setup = """
from Crypto.Cipher import AES
import os
newFile = []
fileData = open('filename').read()
"""
stmt = """
key = os.urandom(32)
cipher = AES.new(key, AES.MODE_CFB)
for lines in fileData:
    newFile = cipher.encrypt(lines)"""

tt = timeit.Timer(stmt, setup)
tt.repeat()
于 2009-11-11T10:51:27.683 回答
0

您可以像这样使用类的setup参数timeit.Timer

tt = timeit.Timer("""
from Crypto.Cipher import AES
import os
newFile = []
key = os.urandom(32)
cipher = AES.new(key, AES.MODE_CFB)
for lines in fileData:
  newFile = cipher.encrypt(lines)""", 
setup = "fileData = open('mytestfile.bmp', 'rb').readlines()")
encryptResult = tt.repeat(1,1)

setup代码只运行一次。

于 2009-11-11T10:59:00.950 回答