Guido van Rossum | f137f75 | 2001-10-04 00:58:24 +0000 | [diff] [blame] | 1 | """Test suite for the profile module.""" |
| 2 | |
| 3 | import profile |
| 4 | |
| 5 | # In order to have reproducible time, we simulate a timer in the global |
| 6 | # variable 'ticks', which represents simulated time in milliseconds. |
| 7 | # (We can't use a helper function increment the timer since it would be |
| 8 | # included in the profile and would appear to consume all the time.) |
| 9 | ticks = 0 |
Tim Peters | 527e64f | 2001-10-04 05:36:56 +0000 | [diff] [blame] | 10 | |
Guido van Rossum | f137f75 | 2001-10-04 00:58:24 +0000 | [diff] [blame] | 11 | def test_main(): |
| 12 | global ticks |
| 13 | ticks = 0 |
| 14 | prof = profile.Profile(timer) |
| 15 | prof.runctx("testfunc()", globals(), globals()) |
| 16 | prof.print_stats() |
| 17 | |
| 18 | def timer(): |
| 19 | return ticks*0.001 |
| 20 | |
| 21 | def testfunc(): |
| 22 | # 1 call |
| 23 | # 1000 ticks total: 400 ticks local, 600 ticks in subfunctions |
| 24 | global ticks |
| 25 | ticks += 199 |
| 26 | helper() # 300 |
| 27 | helper() # 300 |
| 28 | ticks += 201 |
| 29 | |
| 30 | def helper(): |
| 31 | # 2 calls |
| 32 | # 300 ticks total: 40 ticks local, 260 ticks in subfunctions |
| 33 | global ticks |
| 34 | ticks += 1 |
| 35 | helper1() # 30 |
| 36 | ticks += 3 |
| 37 | helper1() # 30 |
| 38 | ticks += 6 |
| 39 | helper2() # 50 |
| 40 | ticks += 5 |
| 41 | helper2() # 50 |
| 42 | ticks += 4 |
| 43 | helper2() # 50 |
| 44 | ticks += 7 |
| 45 | helper2() # 50 |
| 46 | ticks += 14 |
| 47 | |
| 48 | def helper1(): |
| 49 | # 4 calls |
| 50 | # 30 ticks total: 29 ticks local, 1 tick in subfunctions |
| 51 | global ticks |
| 52 | ticks += 10 |
| 53 | hasattr(C(), "foo") |
| 54 | ticks += 19 |
| 55 | |
| 56 | def helper2(): |
| 57 | # 8 calls |
| 58 | # 50 ticks local: 39 ticks local, 11 ticks in subfunctions |
| 59 | global ticks |
| 60 | ticks += 11 |
| 61 | hasattr(C(), "bar") # 1 |
| 62 | ticks += 13 |
| 63 | subhelper() # 10 |
| 64 | ticks += 15 |
| 65 | |
| 66 | def subhelper(): |
| 67 | # 8 calls |
| 68 | # 10 ticks total: 8 ticks local, 2 ticks in subfunctions |
| 69 | global ticks |
| 70 | ticks += 2 |
| 71 | for i in range(2): |
| 72 | try: |
| 73 | C().foo # 1 x 2 |
| 74 | except AttributeError: |
| 75 | ticks += 3 # 3 x 2 |
| 76 | |
| 77 | class C: |
| 78 | def __getattr__(self, name): |
| 79 | # 28 calls |
| 80 | # 1 tick, local |
| 81 | global ticks |
| 82 | ticks += 1 |
| 83 | raise AttributeError |
| 84 | |
| 85 | if __name__ == "__main__": |
| 86 | test_main() |