views:

88

answers:

2

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.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)
A: 

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()
Nadia Alramli
perfect, thanks!
zyrus001
A: 

Hi, 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.

jhwist
Oops, I guess Nadia beat my by a few minutes.
jhwist