나는 아주 이상한 결과를 timeit에서 얻었습니다. 누군가 내가 잘못하고 있는지 말해 줄 수 있습니까? 파이썬 2.7을 사용하고 있습니다. speedtest.py의파이썬 timeit에 대한 놀랄만 한 결과 : counter() 대 defaultdict() vs dict()
import random
to_count = [random.randint(0, 100) for r in range(60)]
이가되는 내용 :
__author__ = 'BlueTrin'
import timeit
def test_init1():
print(timeit.timeit('import speedtest_init'))
def test_counter1():
s = """\
d = defaultdict(int);
for i in speedtest_init.to_count:
d[i] += 1
"""
print(timeit.timeit(s, 'from collections import defaultdict; import speedtest_init;'))
def test_counter2():
print(timeit.timeit('d = Counter(speedtest_init.to_count);', 'from collections import Counter; import speedtest_init;'))
if __name__ == "__main__":
test_init1()
test_counter1()
test_counter2()
콘솔 출력은 다음과 같습니다
C:\Python27\python.exe C:/Dev/codility/chlorum2014/speedtest.py
2.71501962931
65.7090444503
91.2953839048
Process finished with exit code 0
I
이
파일 speedtest_init.py의 내용입니다 기본적으로 timeit()이 코드를 1000000 번 실행하므로 시간을 1000000으로 나눌 필요가 있다고 생각하지만 놀라운 것은 무엇입니까? 카운터가 defaultdict()보다 느리다는 것입니다.예상 되나요?
편집 :
이또한 딕셔너리를 사용하는 것은 defaultdict (INT)보다 빠르다 :
def test_counter3():
s = """\
d = {};
for i in speedtest_init.to_count:
if i not in d:
d[i] = 1
else:
d[i] += 1
"""
print(timeit.timeit(stmt=s, setup='from collections import defaultdict; import speedtest_init;')
이 마지막 버전은 defaultdict (INT)보다 빠른 의미를 좀 더 가독성에 대한 관심을하지 않는 한 당신 defaultdict() 대신 dict()를 사용해야합니다.
내가 다른 테스트와 딕셔너리를 (사용했을)를 defaultdict(), 질문 – BlueTrin
업데이트됩니다 이것은 참으로 놀라운보다 빠릅니다을; 특수 목적의 클래스를 가장 빠른 구현으로 기대할 수 있습니다. 더 빠른 경우'Counter'가 구현에'defaultdict'를 사용하지 않는 이유는 무엇입니까? –
@MarkRansom :'Counter'는'defaultdict'보다 훨씬 많은 일을합니다. 하지만 더 빠른'defaultdict' 서브 클래스로서'Counter'를 생성 할 수 있다면 아마도 패치를 제안 할 수 있습니다. :-) –