wiki:python/timeit

Python Doc


Dictionary mit Platzhaltern durchsuchen

Examples

Measure several methods to sum a list of numbers

see Example in 'sum' entry

Equalize a list with several equal elements

Re: programmierung.in python

module 'equal_items.py'

import sys
import timeit


test = [
    'DK', 'D14', 'D34', 'D14', 'D34', 'D50', 'D81', 'D81', 'D91', 'D91'
]

test_1 = '''\
new = []
for element in test:
    if not element in new:
        new.append(element)
'''

test_2 = '''\
seen = set()
result = list()
for item in test:
    if item not in seen:
        result.append(item)
    seen.add(item)
'''

if __name__ == '__main__':
    length = int(sys.argv[1])
    test = test * length
    print 'test without set: {}'.format(
        timeit.timeit(stmt=test_1,
                      setup='from __main__ import test',
                      number=10000))
    print 'test with    set: {}'.format(
        timeit.timeit(stmt=test_2,
                      setup='from __main__ import test',
                      number=10000))
$ python ./equal_items.py 10
test without set: 0.0989220142365
test with    set: 0.145992994308
Last modified 5 years ago Last modified on May 29, 2014, 7:23:48 PM