1

我正在尝试使用该timeit模块来计时两种插入排序实现的性能。

我想为下面的两个排序函数使用相同的设置数据,所以我想我会创建一个timeit.Timer实例,然后在进行stmt过程中更改实例的属性。这是行不通的。

我得到了相同的结果,这与 default 的结果相同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'
4

0 回答 0