|
7 | 7 | Eventually these will be optimized to work better. |
8 | 8 | """ |
9 | 9 | import sys |
10 | | -sys.path.insert(0, '../') |
11 | 10 |
|
| 11 | +import itertools |
12 | 12 | import random |
13 | | -import cProfile |
| 13 | +import time |
14 | 14 |
|
| 15 | +sys.path.insert(0, '../') |
15 | 16 | import tdl |
16 | 17 |
|
| 18 | +class StopWatch: |
| 19 | + "Simple tool used to count time within a block using the with statement" |
| 20 | + MAXSNAPSHOTS = 10 |
| 21 | + |
| 22 | + def __init__(self): |
| 23 | + self.enterTime = None |
| 24 | + self.snapshots = [] |
| 25 | + |
| 26 | + def __enter__(self): |
| 27 | + self.enterTime = time.clock() |
| 28 | + |
| 29 | + def __exit__(self, *exc): |
| 30 | + self.snapshots.append(time.clock() - self.enterTime) |
| 31 | + if len(self.snapshots) > self.MAXSNAPSHOTS: |
| 32 | + self.snapshots.pop(0) |
| 33 | + |
| 34 | + def getMeanTime(self): |
| 35 | + if not self.snapshots: |
| 36 | + return 0 |
| 37 | + return sum(self.snapshots) / len(self.snapshots) |
| 38 | + |
| 39 | + |
17 | 40 | def main(): |
18 | 41 |
|
19 | 42 | WIDTH = 80 |
20 | 43 | HEIGHT = 60 |
21 | | - |
| 44 | + TOTAL = WIDTH * HEIGHT |
| 45 | + # a list containing all x,y pairs |
| 46 | + CELLS = list(itertools.product(range(WIDTH), range(HEIGHT))) |
| 47 | + |
22 | 48 | console = tdl.init(WIDTH, HEIGHT) |
23 | | - |
| 49 | + fullTimer = StopWatch() |
| 50 | + randomTimer = StopWatch() |
| 51 | + drawTimer = StopWatch() |
| 52 | + flushTimer = StopWatch() |
24 | 53 | while 1: |
25 | 54 | for event in tdl.event.get(): |
26 | 55 | if event.type == tdl.QUIT: |
27 | 56 | raise SystemExit() |
28 | | - for y in range(HEIGHT): |
29 | | - bgcolor = (random.randint(0, 64), random.randint(0, 64), random.randint(0, 64)) |
30 | | - for x in range(WIDTH): |
31 | | - console.drawChar(random.randint(0, 255), fgcolor=(255, 255, 255), bgcolor=bgcolor) |
32 | | - tdl.flush() |
| 57 | + with randomTimer: |
| 58 | + # getrandbits is around 5x faster than using randint |
| 59 | + bgcolors = [(random.getrandbits(6), random.getrandbits(6), random.getrandbits(6)) for _ in range(TOTAL)] |
| 60 | + char = [random.getrandbits(8) for _ in range(TOTAL)] |
| 61 | + with drawTimer: |
| 62 | + for (x,y), bgcolor, char in zip(CELLS, bgcolors, char): |
| 63 | + console.drawChar(char=char, x=x, y=y, fgcolor=(255, 255, 255), bgcolor=bgcolor) |
| 64 | + console.drawStr('Random%7.2fms ' % (randomTimer.getMeanTime() * 1000), 0, 0, tdl.C_WHITE, tdl.C_BLACK) |
| 65 | + console.drawStr('DrawCh%7.2fms ' % (drawTimer.getMeanTime() * 1000), 0, 1, tdl.C_WHITE, tdl.C_BLACK) |
| 66 | + console.drawStr('Flush %7.2fms ' % (flushTimer.getMeanTime() * 1000), 0, 2, tdl.C_WHITE, tdl.C_BLACK) |
| 67 | + with flushTimer: |
| 68 | + tdl.flush() |
33 | 69 | tdl.setTitle('%i FPS' % tdl.getFPS()) |
34 | 70 |
|
35 | 71 | if __name__ == '__main__': |
|
0 commit comments