timeit,对同一个设置字符串使用不同的stmt不起作用

2024-04-29 07:27:12 发布

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

我试图使用timeit模块来计时插入排序的两个实现的性能。你知道吗

我想对下面的两个排序函数使用相同的设置数据,所以我想我只需要创建一个timeit.Timer实例,然后在执行过程中更改实例的stmt属性。这不管用。你知道吗

我得到了相同的结果,这与默认的stmt='pass'的结果相同。你知道吗

然而,当我在设置字符串中测试代码时,它似乎正在工作。你知道吗

import timeit

setup = """
import random


def insort1(seq):
    for a in xrange(1, len(seq)):
        for b in xrange(a, -1, -1):
            if seq[b] < seq[a]:
                break
        else:
            b = -1
        if b + 1 < a:
           seq.insert(b + 1, seq.pop(a))


def insort2(l):
    for i in range(1, len(l)):
        valueToInsert = l[i]
        hole = i
        while hole > 0 and valueToInsert < l[hole - 1]:
            l[hole] = l[hole - 1]
            hole -= 1
        l[hole] = valueToInsert


sorted_samples = [range(100),
          range(1000),
          range(10000)]

reversed_samples = [s[::-1] for s in sorted_samples]

shuffled_samples = map(list, sorted_samples)
for s in shuffled_samples:
    random.shuffle(s)

random_samples = [[random.randint(0, upper) for n in xrange(upper)]
                  for upper in [100, 1000, 10000]]
"""


t = timeit.Timer(setup=setup)
r = 5
n = 1000000
for ind in [0, 1, 2]:

    print 'sample size:100%s\n' % ('0' * ind)

    print '\tinsort1'
    print '\t-------'
    t.stmt = 'insort1(sorted_samples[%s][:])' % ind
    print '\t\tsorted:  ', min(t.repeat(r, n))
    t.stmt = 'insort1(reversed_samples[%s][:])' % ind
    print '\t\treversed:', min(t.repeat(r, n))
    t.stmt = 'insort1(shuffled_samples[%s][:])' % ind
    print '\t\tshuffled:', min(t.repeat(r, n))
    t.stmt = 'insort1(random_samples[%s][:])' % ind
    print '\t\trandom:  ', min(t.repeat(r, n))
    print '\n'

    print '\tinsort2'
    print '\t-------'
    t.stmt = 'insort2(sorted_samples[%s][:])' % ind
    print '\t\tsorted:  ', min(t.repeat(r, n))
    t.stmt = 'insort2(reversed_samples[%s][:])' % ind
    print '\t\treversed:', min(t.repeat(r, n))
    t.stmt = 'insort2(shuffled_samples[%s][:])' % ind
    print '\t\tshuffled:', min(t.repeat(r, n))
    t.stmt = 'insort2(random_samples[%s][:])' % ind
    print '\t\trandom:  ', min(t.repeat(r, n))
    print '\n'

Tags: inforrandomminseqsamplessortedrepeat