Created
February 1, 2012 13:29
-
-
Save btel/1716954 to your computer and use it in GitHub Desktop.
Benchmark graphical libraries in Python
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
<html> | |
<head> | |
<script type="text/javascript"> | |
function run() { | |
setInterval( drawShape, 500 ); | |
} | |
function drawShape(){ | |
// get the canvas element using the DOM | |
var canvas = document.getElementById('mycanvas'); | |
var start = new Date().getTime(); | |
// Make sure we don't execute when canvas isn't supported | |
var i = 0, j = 0; | |
var x, y; | |
var ctx = canvas.getContext('2d'); | |
ctx.beginPath(); | |
for (i=0;i<50000;i++) | |
{ | |
// use getContext to use the canvas for drawing | |
ctx.moveTo(25,25); | |
// Filled triangle | |
for (j=0; j<34; j++) | |
{ | |
x = Math.round(Math.random()*300); | |
y = Math.round(Math.random()*300); | |
ctx.lineTo(x, y); | |
} | |
} | |
ctx.stroke(); | |
var end = new Date().getTime(); | |
document.getElementById('fps').innerHTML = end-start + " ms"; | |
} | |
</script> | |
</head> | |
<body onload="run();"> | |
<canvas id='mycanvas'></canvas> | |
<br> | |
<span id='fps'>t</span> | |
</body> | |
</html> |
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
#!/usr/bin/env python | |
#coding=utf-8 | |
import matplotlib | |
#matplotlib.rcParams.update({'lines.antialiased': False}) | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from matplotlib.collections import LineCollection | |
def line_collection(t, spikes): | |
ax = plt.subplot(111) | |
ts, ns = spikes.shape | |
segs = np.zeros((ns, ts, 2), np.float32) | |
segs[:, :, 1] = spikes.T | |
segs[:, :, 0] = t[:, None].T | |
line_segments = LineCollection(segs) | |
ax.add_collection(line_segments) | |
ax.set_xlim(t.min(), t.max()) | |
ax.set_ylim(spikes.min(), spikes.max()) | |
t = np.linspace(0, np.pi*2, 34) | |
y = np.sin(t) | |
spikes = y[:, None]*np.random.rand(1,50000) | |
import time | |
start1 = time.time() | |
#plt.plot(t, spikes, '-') | |
line_collection(t, spikes) | |
start2 = time.time() | |
plt.savefig('plot_perf.png') | |
stop = time.time() | |
print 'Plotting:', -start1+start2 | |
print 'Exporting:', -start2+stop | |
print 'total:', -start1+stop | |
print matplotlib.get_backend() | |
plt.show() |
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
#!/usr/bin/env python | |
from OpenGL.GL import * | |
from OpenGL.GLUT import * | |
from OpenGL.GLU import * | |
OpenGL.ERROR_ON_COPY = True | |
import sys | |
# Some api in the chain is translating the keystrokes to this octal string | |
# so instead of saying: ESCAPE = 27, we use the following. | |
ESCAPE = '\033' | |
# Number of the glut window. | |
window = 0 | |
# A general OpenGL initialization function. Sets all of the initial parameters. | |
def InitGL(Width, Height): # We call this right after our OpenGL window is created. | |
glClearColor(0.0, 0.0, 0.0, 0.0) # This Will Clear The Background Color To Black | |
glClearDepth(1.0) # Enables Clearing Of The Depth Buffer | |
glDepthFunc(GL_LESS) # The Type Of Depth Test To Do | |
glEnable(GL_DEPTH_TEST) # Enables Depth Testing | |
glShadeModel(GL_SMOOTH) # Enables Smooth Color Shading | |
glMatrixMode(GL_PROJECTION) | |
glLoadIdentity() # Reset The Projection Matrix | |
# Calculate The Aspect Ratio Of The Window | |
gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0) | |
glMatrixMode(GL_MODELVIEW) | |
# The function called when our window is resized (which shouldn't happen if you enable fullscreen, below) | |
def ReSizeGLScene(Width, Height): | |
if Height == 0: # Prevent A Divide By Zero If The Window Is Too Small | |
Height = 1 | |
glViewport(0, 0, Width, Height) # Reset The Current Viewport And Perspective Transformation | |
glMatrixMode(GL_PROJECTION) | |
glLoadIdentity() | |
gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0) | |
glMatrixMode(GL_MODELVIEW) | |
# The main drawing function. | |
def DrawGLScene(): | |
# Clear The Screen And The Depth Buffer | |
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) | |
glLoadIdentity() # Reset The View | |
# Move Left 1.5 units and into the screen 6.0 units. | |
glTranslatef(0, 0.0, -4.0) | |
# Draw a triangle | |
import time | |
import numpy as np | |
n_pts = 34 | |
n_spikes =50000 | |
t = np.linspace(-2, 2, n_pts) | |
y= 1.5*(2*np.random.rand(n_pts,n_spikes)-1) | |
start = time.time() | |
vertices = np.empty((n_spikes, n_pts, 2), dtype=np.float) | |
vertices[:,:,0] = t[:, None].T | |
vertices[:,:,1] = y.T | |
vertices = vertices.reshape(-1, 2) | |
glEnableClientState(GL_VERTEX_ARRAY) | |
glVertexPointer(2, GL_FLOAT, 0, vertices) | |
for i in xrange(n_spikes): | |
glDrawArrays(GL_LINE_STRIP, i*n_pts, n_pts) | |
glDisableClientState(GL_VERTEX_ARRAY); | |
# since this is double buffered, swap the buffers to display what just got drawn. | |
glutSwapBuffers() | |
print "It took:", time.time()-start, 's' | |
# The function called whenever a key is pressed. Note the use of Python tuples to pass in: (key, x, y) | |
def keyPressed(*args): | |
# If escape is pressed, kill everything. | |
if args[0] == ESCAPE: | |
glutDestroyWindow(window) | |
sys.exit() | |
def main(): | |
global window | |
# For now we just pass glutInit one empty argument. I wasn't sure what should or could be passed in (tuple, list, ...) | |
# Once I find out the right stuff based on reading the PyOpenGL source, I'll address this. | |
glutInit(()) | |
# Select type of Display mode: | |
# Double buffer | |
# RGBA color | |
# Alpha components supported | |
# Depth buffer | |
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH) | |
# get a 640 x 480 window | |
glutInitWindowSize(800, 600) | |
# the window starts at the upper left corner of the screen | |
glutInitWindowPosition(0, 0) | |
# Okay, like the C version we retain the window id to use when closing, but for those of you new | |
# to Python (like myself), remember this assignment would make the variable local and not global | |
# if it weren't for the global declaration at the start of main. | |
window = glutCreateWindow("Jeff Molofee's GL Code Tutorial ... NeHe '99") | |
# Register the drawing function with glut, BUT in Python land, at least using PyOpenGL, we need to | |
# set the function pointer and invoke a function to actually register the callback, otherwise it | |
# would be very much like the C version of the code. | |
glutDisplayFunc (DrawGLScene) | |
# Uncomment this line to get full screen. | |
#glutFullScreen() | |
# When we are doing nothing, redraw the scene. | |
glutIdleFunc(DrawGLScene) | |
# Register the function called when our window is resized. | |
glutReshapeFunc (ReSizeGLScene) | |
# Register the function called when the keyboard is pressed. | |
glutKeyboardFunc (keyPressed) | |
# Initialize our window. | |
InitGL(800, 600) | |
# Start Event Processing Engine | |
glutMainLoop() | |
# Print message to console, and kick off the main to get it rolling. | |
print "Hit ESC key to quit." | |
main() | |
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
#!/usr/bin/env python | |
#coding=utf-8 | |
import matplotlib | |
#matplotlib.rcParams.update({'lines.antialiased': False}) | |
matplotlib.use('MacOSX') | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from matplotlib.collections import LineCollection | |
from PIL import Image, ImageDraw, ImageTk | |
import Tkinter as tk | |
im = Image.new('RGBA', (800, 600)) | |
draw=ImageDraw.Draw(im) | |
root= tk.Tk() | |
def plot(t, spikes, size): | |
nx, ny = size | |
ts, ns = spikes.shape | |
xmin, xmax = t.min(), t.max() | |
ymin, ymax = spikes.min(), spikes.max() | |
spikes = (1-(spikes-ymin)/(ymax-ymin))*ny | |
t = (t-xmin)/(xmax-xmin)*nx | |
segs = np.empty((ns, ts, 2), np.float32) | |
segs[:, :, 1] = spikes.T | |
segs[:, :, 0] = t[:, None].T | |
for i in xrange(ns): | |
draw.line(segs[i,:,:]) | |
def show(): | |
root.tkIm = ImageTk.PhotoImage(im) | |
root.label_image = tk.Label(root, image=root.tkIm) | |
root.label_image.pack() | |
root.update() | |
t = np.linspace(0, np.pi*2, 34) | |
y = np.sin(t) | |
spikes = y[:, None]*np.random.rand(1,50000) | |
import time | |
start1 = time.time() | |
#plt.plot(t, spikes, '-') | |
plot(t, spikes, (800, 600)) | |
start2 = time.time() | |
show() | |
stop = time.time() | |
print 'Plotting:', -start1+start2 | |
print 'Exporting:', -start2+stop | |
print 'total:', -start1+stop | |
root.mainloop() |
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
#!/usr/bin/env python | |
#coding=utf-8 | |
# Sample Python/Pygame Programs | |
# Simpson College Computer Science | |
# http://cs.simpson.edu | |
import pygame | |
# Define some colors | |
black = ( 0, 0, 0) | |
white = ( 255, 255, 255) | |
green = ( 0, 255, 0) | |
red = ( 255, 0, 0) | |
pygame.init() | |
# Set the height and width of the screen | |
size=[700,500] | |
screen=pygame.display.set_mode(size) | |
pygame.display.set_caption("My Game") | |
#Loop until the user clicks the close button. | |
done=False | |
# Used to manage how fast the screen updates | |
clock=pygame.time.Clock() | |
import numpy as np | |
import time | |
# -------- Main Program Loop ----------- | |
while done==False: | |
for event in pygame.event.get(): # User did something | |
if event.type == pygame.QUIT: # If user clicked close | |
done=True # Flag that we are done so we exit this loop | |
# Set the screen background | |
screen.fill(black) | |
# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT | |
segs = np.random.rand(30, 50000, 2)*np.array(size)[None, None, :] | |
start = time.time() | |
for i in xrange(segs.shape[1]): | |
pygame.draw.lines(screen,green, False, segs[:,i,:],1) | |
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT | |
# Limit to 20 frames per second | |
clock.tick(20) | |
# Go ahead and update the screen with what we've drawn. | |
pygame.display.flip() | |
print "It took:", time.time()-start, 's' | |
# Be IDLE friendly. If you forget this line, the program will 'hang' | |
# on exit. | |
pygame.quit () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Neat. A results file would be nice.