不能将数据对象与时间。时间python中的模块

2024-04-25 04:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这很好(定时文件读取操作):

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

因为我无法访问'fileData'对象,所以下面的命令不起作用。我不能从timeit函数内部再次创建它,否则它将增加整个执行时间。在

定时加密操作:

^{pr2}$

Tags: 文件数据对象close时间opentimertimeit
2条回答

您可以使用timeit.Timer类的setup参数,如下所示:

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代码只运行一次。在

timeit接受只运行一次的设置参数

从文件中:

setup: statement to be executed once initially (default 'pass')

例如:

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()

相关问题 更多 >