開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART III.(Functions and Generators)、CHAPTER 21(The Benchmarking Interlude)、Test Your Knowledge: Quizを解いてみる。
その他参考書籍
Test Your Knowledge: Quiz
コード(BBEdit)
sample.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import sys import timeit l = list(range(1000)) for_loop = ''' res = [] for x in {0}:res.append(abs(x)) '''.format(l) list_comp = 'res = [abs(x) for x in {0}]'.format(l) map_call = 'res = list(map(abs, {0}))'.format(l) gen_expr = 'res = list(abs(x) for x in {0})'.format(l) gen_func = ''' def genFunc(): def gen(): for x in {0}: yield abs(x) return list(gen()) res = genFunc()'''.format(l) print(sys.version) for key, value in {'for loop':for_loop, 'list comprehension': list_comp, 'map call':map_call, 'generator expression': gen_expr, 'generator function': gen_func}.items(): print('{0:20s}: {1}'.format( key, min(timeit.repeat(stmt=value, number=10000, repeat=3))))
入出力結果(Terminal)
$ ./sample.py 3.3.5 (default, Mar 15 2014, 14:51:54) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] map call : 1.6910948629956692 for loop : 3.3138353760004975 list comprehension : 2.129166583006736 generator expression: 2.8622112959856167 generator function : 2.8779427589906845 $
結果を確認すると、list comprehensionよりmapの方が速かった。
generatorを使ったのが、for loopのより速いのは意外な感じ。
0 コメント:
コメントを投稿