defsetUp(self): '''before each test function''' pass
deftearDown(self): '''after each test function''' pass
deftest_func(self): n = 10 # 我们要求他们生成的结果是一样的 flag = (loop_for(n) == loop_while(n) == loop_generator(n) == loop_list_compre(n) == loop_map(n)) self.assertTrue(flag)
import timeit
defprint_func_run_time(count, func, **kw): b = timeit.default_timer() for i in range(count): func(**kw) print('{} run {} times used {}s'.format( func.__name__.ljust(20), count, timeit.default_timer() -b ))
if __name__ == "__main__": count = 1000 n = 1000 print_func_run_time(count, loop_for, n = n) print_func_run_time(count, loop_while, n = n) print_func_run_time(count, loop_generator, n = n) print_func_run_time(count, loop_list_compre, n = n) print_func_run_time(count, loop_map, n = n) unittest.main()
# . # ---------------------------------------------------------------------- # Ran 1 test in 0.000s # # OK # loop_for run 1000 times used 0.14018906400087872s # loop_while run 1000 times used 0.21399457900042762s # loop_generator run 1000 times used 0.12857274799898732s # loop_list_compre run 1000 times used 0.08585307099929196s # loop_map run 1000 times used 0.043123570998432115s
我们以性能好坏来区分,得到的结论
1
map > 列表解析 > 生成器 > for > while
map 是内置函数,底层由 C 来编写,最快是毫无疑问的。而 while 是纯 Python 实现的,所以性能最差。
defloop_generator(n): res = (abs(i) for i in range(n)) return res
defloop_list_compre(n): res = [abs(i) for i in range(n)] return res
defloop_map(n): return map(abs, range(n))
import timeit
defprint_func_run_time(count, func, **kw): b = timeit.default_timer() for i in range(count): func(**kw) print('{} run {} times used {}s'.format( func.__name__.ljust(20), count, timeit.default_timer() -b ))
if __name__ == "__main__": count = 1000 n = 1000 print_func_run_time(count, loop_list_compre, n = n) print_func_run_time(count, loop_map, n = n) print_func_run_time(count, loop_generator, n = n)
# loop_list_compre run 1000 times used 0.08865494900237536s # loop_map run 1000 times used 0.0007684140000492334s # loop_generator run 1000 times used 0.0009459810025873594s