Уведомления

Группа в Telegram: @pythonsu

#1 Май 7, 2015 12:27:09

Wild_Egg
Зарегистрирован: 2015-05-07
Сообщения: 1
Репутация: +  0  -
Профиль   Отправить e-mail  

Timeit

Добрый день) нуждаюсь в совете)
Суть такова. В приведенном ниже коде, четыре нагло сворованные алгоритма сортировки. Надо тестировать их на скорость выполнения. Но тут у модуля Timeit проявилась одна особенность) При общем параметре setup для всех четырех stmt, при каждом присваивании speed1 speed2 speed3 speed4, функция заходит заново в setup, соответственно генерирует новую последовательность) А это не есть хорошо, идея состоит в том что бы тестировать 4 алгоритма на одной и той же сгенерированной последовательности)

import timeit
setup = '''
import random
Generator = [random.randint(1,100) for i in range(10)]
'''
stmt = '''
def buble():
        li=Generator.copy()
        n = 1
        global count_sr1,count_ob1
        count_sr1=0
        count_ob1=0
        while n < len(li):
                 count_sr1=count_sr1+1
                 for i in range(len(li)-n):
                    if li[i] > li[i+1]:
                            count_sr1=count_sr1+1
                            li[i],li[i+1] = li[i+1],li[i]
                            count_ob1=count_ob1+1
                 n += 1
        return li
print('Исходный массив')
print(Generator)
print('Buble sort')
print(buble())
print('Количество сравнений',count_sr1)
print('Количество обменов',count_ob1)
'''
speed=timeit.timeit(stmt,setup,number=1)
print('Скорость сортировки',speed)
print()
stmt = '''
def select():
    global count_sr2,count_ob2
    count_sr2=0
    count_ob2=0
    s=Generator.copy()
    for k in range(len(s) - 1):
        m = k
        i = k + 1
        while i < len(s):
            count_sr2=count_sr2+1
            if s[i] < s[m]:
                count_sr2=count_sr2+1
                m = i
            i += 1
        t = s[k]
        s[k] = s[m]
        count_ob2=count_ob2+1
        s[m] = t
        count_ob2=count_ob2+1
    return s
print('Исходный массив')
print(Generator)
print('Selection sort')
print(select())
print('Количество сравнений',count_sr2)
print('Количество обменов',count_ob2)
'''
speed2=timeit.timeit(stmt,setup,number=1)
print('Скорость сортировки',speed2)
print()
stmt = '''
def insert():
    global count_sr3,count_ob3
    count_sr3=0
    count_ob3=0
    ins=Generator.copy()
    for i in range(1, len(ins)):
        j = i - 1
        value = ins.pop(i)
        count_ob3=count_ob3+1
        while (j >= 0) and (ins[j] > value):
            count_sr3=count_sr3+2
            j -= 1
        ins.insert(j + 1, value)
        count_ob3=count_ob3+1
    return ins
print('Исходный массив')
print(Generator)
print('Insertion_sort')
print(insert())
print('Количество сравнений',count_sr3)
print('Количество обменов',count_ob3)
'''
speed3=timeit.timeit(stmt,setup,number=1)
print('Скорость сортировки',speed3)
print()
stmt='''
def cock():
    global count_sr4,count_ob4
    count_sr4=0
    count_ob4=0
    c=Generator.copy()
    for k in range(len(c)-1, 0, -1):
        swapped = False
        for i in range(k, 0, -1):
            if c[i]<c[i-1]:
                count_sr4=count_sr4+1            
                a = c[i]
                count_ob4=count_ob4+1
                b = c[i-1]
                count_ob4=count_ob4+1
                c[i] = b
                count_ob4=count_ob4+1
                c[i-1] = a
                count_ob4=count_ob4+1
                swapped = True
 
        for i in range(k):
            if c[i] > c[i+1]:
                count_sr4=count_sr4+1
                a = c[i]
                count_ob4=count_ob4+1
                b = c[i+1]
                count_ob4=count_ob4+1
                c[i] = b
                count_ob4=count_ob4+1
                c[i+1] = a
                count_ob4=count_ob4+1
                swapped = True
 
        if not swapped:
            return c
print('Исходный массив')
print(Generator)
print('Cocktail_sort')
print(cock())
print('Количество сравнений',count_sr4)
print('Количество обменов',count_ob4)
'''
speed4=timeit.timeit(stmt,setup,number=1)
print('Скорость сортировки',speed4)
print()

Собственно интересует, как это лечиться, и лечиться ли вообще)
Конструктивная критика приветствуется)
Спасибо

Отредактировано Wild_Egg (Май 7, 2015 12:30:49)

Офлайн

#2 Май 7, 2015 12:41:53

FishHook
От:
Зарегистрирован: 2011-01-08
Сообщения: 8312
Репутация: +  568  -
Профиль   Отправить e-mail  

Timeit

import random
s = [random.randint(1, 100) for i in range(10)]
def test1():
    print s
def test2():
    print s
if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test1()", setup="from __main__ import test1", number=1))
    print(timeit.timeit("test2()", setup="from __main__ import test2", number=1))



Офлайн

#3 Май 7, 2015 12:47:12

py.user.next
От:
Зарегистрирован: 2010-04-29
Сообщения: 10016
Репутация: +  857  -
Профиль   Отправить e-mail  

Timeit

У меня такой шаблон.

#!/usr/bin/env python3
 
import timeit
 
 
def f1():
    pass
 
def f2():
    pass
 
 
def main():
    t1 = timeit.Timer('f1()', 'from __main__ import f1')
    t2 = timeit.Timer('f2()', 'from __main__ import f2')
 
    for t in t1, t2:
        print(t.repeat(3, 10000))
 
if __name__ == '__main__':
    main()

Там можешь генерацию разместить в глобальной области, а сравниваемые функции - в f1, f2, …



Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version