# -- coding: utf-8 -- import cProfile import pstats left_column_width = 40 loop_range = range(10000000) class A: def __init__(self): self.x = 1 def test1(): for z in loop_range: pass def test2(): y = A() for z in loop_range: if y.x: pass def test3(): y = A() x = y.x for z in loop_range: if x: pass test1_profile = cProfile.Profile() test1_profile.runcall(test1) test1_profile.print_stats(sort='cumtime') test2_profile = cProfile.Profile() test2_profile.runcall(test2) test2_profile.print_stats(sort='cumtime') test3_profile = cProfile.Profile() test3_profile.runcall(test3) test3_profile.print_stats(sort='cumtime') print('number of loops:'.ljust(left_column_width, ' '), len(loop_range), '\n') print("pass:".ljust(left_column_width, ' '), pstats.Stats(test1_profile).total_tt) print("if y.x:".ljust(left_column_width, ' '), pstats.Stats(test2_profile).total_tt) print("if x:".ljust(left_column_width, ' '), pstats.Stats(test3_profile).total_tt, '\n')