Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though f
(context)
| 23 | |
| 24 | |
| 25 | def inputhook(context): |
| 26 | """Run the pyglet event loop by processing pending events only. |
| 27 | |
| 28 | This keeps processing pending events until stdin is ready. After |
| 29 | processing all pending events, a call to time.sleep is inserted. This is |
| 30 | needed, otherwise, CPU usage is at 100%. This sleep time should be tuned |
| 31 | though for best performance. |
| 32 | """ |
| 33 | # We need to protect against a user pressing Control-C when IPython is |
| 34 | # idle and this is running. We trap KeyboardInterrupt and pass. |
| 35 | try: |
| 36 | t = clock() |
| 37 | while not context.input_is_ready(): |
| 38 | pyglet.clock.tick() |
| 39 | for window in pyglet.app.windows: |
| 40 | window.switch_to() |
| 41 | window.dispatch_events() |
| 42 | window.dispatch_event("on_draw") |
| 43 | flip(window) |
| 44 | |
| 45 | # We need to sleep at this point to keep the idle CPU load |
| 46 | # low. However, if sleep to long, GUI response is poor. As |
| 47 | # a compromise, we watch how often GUI events are being processed |
| 48 | # and switch between a short and long sleep time. Here are some |
| 49 | # stats useful in helping to tune this. |
| 50 | # time CPU load |
| 51 | # 0.001 13% |
| 52 | # 0.005 3% |
| 53 | # 0.01 1.5% |
| 54 | # 0.05 0.5% |
| 55 | used_time = clock() - t |
| 56 | if used_time > 10.0: |
| 57 | # print('Sleep for 1 s') # dbg |
| 58 | time.sleep(1.0) |
| 59 | elif used_time > 0.1: |
| 60 | # Few GUI events coming in, so we can sleep longer |
| 61 | # print('Sleep for 0.05 s') # dbg |
| 62 | time.sleep(0.05) |
| 63 | else: |
| 64 | # Many GUI events coming in, so sleep only very little |
| 65 | time.sleep(0.001) |
| 66 | except KeyboardInterrupt: |
| 67 | pass |