简体   繁体   English

带有timeit的Python循环基准测试

[英]Python loop benchmark with timeit

I would like to benchmark a specific code segment inside a for loop in Python. 我想在Python的for循环中对特定的代码段进行基准测试。 I am using timeit as follows: 我正在使用timeit ,如下所示:

def createTokens():
    keypath=('./pickles/key.pickle')
    path="./data/"
    directory = os.listdir(path)
    tok={}
    print('create tokens..')
    t=[2**4,2**5,2**6,2**7,2**8,2**9,2**10,2**12,2**14,2**16]
    files=['pl_10000004','pl_10000002','pl_100000026']
    for filename in files:
        for i in t:
            code='etok=utils.token(filename,keypath,str(i))'
            t = timeit.Timer(stmt=code,setup='from __main__ import utils')
            print(filename+'_'+str(i)+'.pickle')
            print ('%f'%float(t.timeit(10/10)))

However this raises: 但是,这引起了:

NameError: global name 'filename' is not defined

when I include filename in setup variable Python says: 当我在设置变量中包含文件名时,Python表示:

ImportError: cannot import name filename

How is this is solved? 这怎么解决?

filename isn't defined in the scope of the code in the timeit block. filename未在timeit块的代码范围内定义。 I don't know what utils is in your code, but assuming it expects filename and keypath as strings just replace your 我不知道是什么utils是在你的代码,但假设,预计filenamekeypath为字符串只需更换您的

    code='etok=utils.token(filename,keypath,str(i))'

line with: 符合:

    code='etok=utils.token("{}","{}",{})'.format(filename, keypath, i)

Try this: 尝试这个:

code='etok=utils.token("%s","%s","%s")' % (filename, keypath, i)

This will allow you to create a code string that has the values you want. 这将允许您创建具有所需值的代码字符串。 Also, by using the %s conversion, i is coerced into a str type for you. 另外,通过使用%s转换, i被强制转换为str类型。

Edit: Added double quotes around values. 编辑:在值周围添加了双引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM