Created
January 5, 2014 19:43
-
-
Save mjdarby/8272852 to your computer and use it in GitHub Desktop.
Measuring the length of time taken to get through N key state tests in the Hullet Bells input handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pygame, time | |
from pygame.locals import * | |
class InputCallback: | |
def __init__(self, key, callback): | |
self.key = key | |
self.callback = callback | |
class InputHandler: | |
def __init__(self): | |
self.keydownCallbacks = [] | |
self.keyupCallbacks = [] | |
self.perframeCallbacks = [] | |
self.quitCallback = None | |
def update(self): | |
# Run event-based callbacks | |
events = pygame.event.get() | |
for event in events: | |
if event.type == pygame.KEYDOWN: | |
for keydownCallback in self.keydownCallbacks: | |
if keydownCallback.key == event.key: | |
keydownCallback.callback() | |
elif event.type == pygame.KEYUP: | |
for keyupCallback in self.keyupCallbacks: | |
if keyupCallback.key == event.key: | |
keyupCallback.callback() | |
elif event.type == pygame.QUIT: | |
if self.quitCallback: | |
self.quitCallback.callback() | |
# Run keystate-based callbacks | |
keystates = pygame.key.get_pressed() | |
for perframeCallback in self.perframeCallbacks: | |
if keystates[perframeCallback.key]: | |
perframeCallback.callback() | |
def addEventCallback(self, callback, key, event): | |
inputCallback = InputCallback(key, callback) | |
if event == pygame.KEYDOWN: | |
self.keydownCallbacks.append(inputCallback) | |
elif event == pygame.KEYUP: | |
self.keyupCallbacks.append(inputCallback) | |
def setQuitCallback(self, callback): | |
inputCallback = InputCallback(None, callback) | |
self.quitCallback = inputCallback | |
def addPerFrameCallback(self, callback, key): | |
inputCallback = InputCallback(key, callback) | |
self.perframeCallbacks.append(inputCallback) | |
def nothing(): | |
pass | |
def main(): | |
pygame.init() | |
for numKeys in range(323): | |
inputHandler = InputHandler() | |
times = [] | |
for i in range(numKeys): | |
inputHandler.addPerFrameCallback(nothing, i) | |
for i in range(100000): | |
startTime = time.clock() | |
inputHandler.update() | |
endTime = time.clock() | |
times.append((endTime - startTime) * 1000000) | |
print numKeys,reduce(lambda x, y: x + y, times) / len(times) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment