开发者

Can't use a data obj with timeit.Time module in python

I'm trying to measure how long it takes read then encrypt some data (independently). But I can't seem to access the a pre-created data obj within timeit (as it runs in its own virtual environment)

This works fine (timing file read operation):

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

The the below doesn't work because I can't access 'fileData' obj. I can't create it again from inside the timeit function, otherwise it will increase the overall execution time.

timing encrypt operation:

tt = timeit.Timer("""
from Crypto.Ciphe开发者_运维知识库r 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)


timeit takes a setup argument that only runs once

from the docs:

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

for example:

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


you can use the setup parameter of the timeit.Timer class like so:

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)

The setup code is only run once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜