[pypy-svn] r74381 - in pypy/extradoc/talk/pycon-italy-2010/pypy_demo: . manderlbrot

antocuni at codespeak.net antocuni at codespeak.net
Wed May 5 17:00:05 CEST 2010


Author: antocuni
Date: Wed May  5 17:00:04 2010
New Revision: 74381

Added:
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/__init__.py   (contents, props changed)
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manage.py   (contents, props changed)
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/__init__.py   (contents, props changed)
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/models.py   (contents, props changed)
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/py_kohn_bmp.py   (contents, props changed)
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/py_mandel.py   (contents, props changed)
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/tests.py   (contents, props changed)
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/views.py   (contents, props changed)
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/settings.py   (contents, props changed)
   pypy/extradoc/talk/pycon-italy-2010/pypy_demo/urls.py   (contents, props changed)
Log:
a simple django demo that is faster on pypy than cpython.  Moreover, it also
shows how to run the application on cpython, but delegate the computational
intensive tasks to pypy, through execnet



Added: pypy/extradoc/talk/pycon-italy-2010/pypy_demo/__init__.py
==============================================================================

Added: pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manage.py
==============================================================================
--- (empty file)
+++ pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manage.py	Wed May  5 17:00:04 2010
@@ -0,0 +1,11 @@
+#!/usr/bin/python
+from django.core.management import execute_manager
+try:
+    import settings # Assumed to be in the same directory.
+except ImportError:
+    import sys
+    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+    sys.exit(1)
+
+if __name__ == "__main__":
+    execute_manager(settings)

Added: pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/__init__.py
==============================================================================

Added: pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/models.py
==============================================================================
--- (empty file)
+++ pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/models.py	Wed May  5 17:00:04 2010
@@ -0,0 +1,3 @@
+from django.db import models
+
+# Create your models here.

Added: pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/py_kohn_bmp.py
==============================================================================
--- (empty file)
+++ pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/py_kohn_bmp.py	Wed May  5 17:00:04 2010
@@ -0,0 +1,111 @@
+
+# py_kohn_bmp - Copyright 2007 by Michael Kohn
+# http://www.mikekohn.net/
+# mike at mikekohn.net
+#
+# Feel free to use this class in your own programs (commerical or not)
+# as long as you don't remove my name, email address, webpage, or copyright.
+#
+# Example how to use:
+#
+# my_bmp.kohn_bmp("out.bmp",image_width,image_height,3) <-- depth of 3 is color
+# my_bmp.write_pixel(red,green,blue)  <-- do this width*height times
+# my_bmp.close()
+#
+# if depth is set to 1 (black and white image) call write_pixel_bw(y) where
+# y is between 0 and 255
+
+# adapted by Antonio Cuni - 2010
+
+from cStringIO import StringIO
+
+class kohn_bmp:
+  out=0
+  width=0
+  height=0
+  depth=0
+  bytes=0
+  xpos=0
+  width_bytes=0
+
+  def write_int(self,n):
+    str_out='%c%c%c%c' % ((n&255),(n>>8)&255,(n>>16)&255,(n>>24)&255)
+    self.out.write(str_out)
+
+  def write_word(self,n):
+    str_out='%c%c' % ((n&255),(n>>8)&255)
+    self.out.write(str_out)
+
+  def __init__(self,width,height,depth):
+    self.width=width
+    self.height=height
+    self.depth=depth
+
+    self.width_bytes=width*depth
+    if (self.width_bytes%4)!=0:
+      self.width_bytes=self.width_bytes+(4-(self.width_bytes%4))
+
+    self.out=StringIO()
+    self.out.write("BM")          # magic number
+    if depth==1:
+      self.write_int((self.width_bytes*height)+54+1024)
+    else:
+      self.write_int((self.width_bytes*height)+54)
+    self.write_word(0)
+    self.write_word(0)
+    if depth==1:
+      self.write_int(54+1024)
+    else:
+      self.write_int(54)
+
+    self.write_int(40)                 # header_size
+    self.write_int(width)              # width
+    self.write_int(height)             # height
+    self.write_word(1)                 # planes
+    self.write_word(depth*8)           # bits per pixel
+    self.write_int(0)                  # compression
+    self.write_int(self.width_bytes*height*depth) # image_size
+    self.write_int(0)                  # biXPelsperMetre
+    self.write_int(0)                  # biYPelsperMetre
+
+    if depth==1:
+      self.write_int(256)              # colors used
+      self.write_int(256)              # colors important
+
+      for c in range(256):
+        self.out.write('%c' % c)
+        self.out.write('%c' % c)
+        self.out.write('%c' % c)
+        self.out.write('%c' % 0)
+
+    else:
+      self.write_int(0)                # colors used - 0 since 24 bit
+      self.write_int(0)                # colors important - 0 since 24 bit
+
+
+  def write_pixel_bw(self,y):
+    self.out.write(str("%c" % y))
+    self.xpos=self.xpos+1
+    if self.xpos==self.width:
+      while self.xpos<self.width_bytes:
+        self.out.write(str("%c" % 0))
+        self.xpos=self.xpos+1
+      self.xpos=0
+
+  def write_pixel(self,red,green,blue):
+    self.out.write(str("%c" % (blue&255)))
+    self.out.write(str("%c" % (green&255)))
+    self.out.write(str("%c" % (red&255)))
+    self.xpos=self.xpos+1
+    if self.xpos==self.width:
+      self.xpos=self.xpos*3
+      while self.xpos<self.width_bytes:
+        self.out.write(str("%c" % 0))
+        self.xpos=self.xpos+1
+      self.xpos=0
+
+  def dump(self):
+    v = self.out.getvalue()
+    self.out.close()
+    return v
+ 

Added: pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/py_mandel.py
==============================================================================
--- (empty file)
+++ pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/py_mandel.py	Wed May  5 17:00:04 2010
@@ -0,0 +1,49 @@
+#!/usr/bin/python
+
+import cStringIO
+from py_kohn_bmp import kohn_bmp
+
+## PyMandel - Mandelbrots generated in Python
+## Copyright 2007 - Michael Kohn
+## mike at mikekohn.net - http://www.mikekohn.net/
+## adapted by Antonio Cuni - 2010
+
+# Changing the values below will change the resulting image
+
+def manderlbrot(image_width, image_height):
+    start_real=-2.00
+    start_imag=-1.00
+    end_real=1.00
+    end_imag=1.00
+
+    my_bmp=kohn_bmp(image_width,image_height,3)
+
+    colors = [ [0,0,0], [255,0,0], [127,0,0], 
+               [127,127,0], [0,127,0], [0,255,0],
+               [0,255,0], [0,255,127], [0,127,127],
+               [0,127,255], [0,0,255], [127,0,255],
+               [127,0,255], [255,0,255], [255,0,127],
+               [127,127,0], [255,0,0] ]
+
+    inc_real=(end_real-start_real)/image_width
+    inc_imag=(end_imag-start_imag)/image_height
+
+    start=complex(start_real,start_imag)
+    end=complex(end_real,end_imag)
+
+    for y in range(image_height):
+        for x in range(image_width):
+            c=complex(start_real+(inc_real*x),start_imag+(inc_imag*y))
+            z=complex(0,0)
+            count=169
+
+            while count>0:
+                z=(z**2)+c
+                if abs(z)>2: break
+                count=count-1
+
+            c=int(count/10)
+            my_bmp.write_pixel(colors[c][0],colors[c][1],colors[c][2])
+
+    return my_bmp.dump()
+

Added: pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/tests.py
==============================================================================
--- (empty file)
+++ pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/tests.py	Wed May  5 17:00:04 2010
@@ -0,0 +1,23 @@
+"""
+This file demonstrates two different styles of tests (one doctest and one
+unittest). These will both pass when you run "manage.py test".
+
+Replace these with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.failUnlessEqual(1 + 1, 2)
+
+__test__ = {"doctest": """
+Another way to test that 1 + 1 is equal to 2.
+
+>>> 1 + 1 == 2
+True
+"""}
+

Added: pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/views.py
==============================================================================
--- (empty file)
+++ pypy/extradoc/talk/pycon-italy-2010/pypy_demo/manderlbrot/views.py	Wed May  5 17:00:04 2010
@@ -0,0 +1,52 @@
+# Create your views here.
+
+from django.http import HttpResponse
+
+# only for benchmarking purposes
+def empty(request):
+    return HttpResponse('')
+
+# render a manderlbrot image
+def render(request):
+    w = int(request.GET.get('w', 320))
+    h = int(request.GET.get('h', 240))
+
+    from py_mandel import manderlbrot
+    img = manderlbrot(w, h)
+    return HttpResponse(img, content_type="image/bmp")
+
+
+# render a manderlbrot image through the execnet pypy child, which is set up
+# below
+def pypy_render(request):
+    w = int(request.GET.get('w', 320))
+    h = int(request.GET.get('h', 240))
+
+    channel = pypy.remote_exec("""
+        from py_mandel import manderlbrot
+        w, h = channel.receive()
+        img = manderlbrot(w, h)
+        channel.send(img)
+    """)
+    channel.send((w, h))
+    img = channel.receive()
+    return HttpResponse(img, content_type="image/bmp")
+    
+
+# setup execnet and pypy child
+#
+# The setup is done here so that a single pypy-c is started and reused for all
+# requests.  sys.path and cwd are set up so that py_mandel can be imported
+# from remote_exec
+
+import execnet
+mygroup = execnet.Group()
+pypy = mygroup.makegateway("popen//python=pypy-c")
+pypy.remote_exec("""
+    import sys
+    import os
+    os.chdir("manderlbrot")
+    sys.path.insert(0, '')
+""")
+
+

Added: pypy/extradoc/talk/pycon-italy-2010/pypy_demo/settings.py
==============================================================================
--- (empty file)
+++ pypy/extradoc/talk/pycon-italy-2010/pypy_demo/settings.py	Wed May  5 17:00:04 2010
@@ -0,0 +1,80 @@
+# Django settings for pypy_demo project.
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+ADMINS = (
+    # ('Your Name', 'your_email at domain.com'),
+)
+
+MANAGERS = ADMINS
+
+DATABASE_ENGINE = ''           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+DATABASE_NAME = ''             # Or path to database file if using sqlite3.
+DATABASE_USER = ''             # Not used with sqlite3.
+DATABASE_PASSWORD = ''         # Not used with sqlite3.
+DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
+DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.
+
+# Local time zone for this installation. Choices can be found here:
+# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
+# although not all choices may be available on all operating systems.
+# If running in a Windows environment this must be set to the same as your
+# system time zone.
+TIME_ZONE = 'America/Chicago'
+
+# Language code for this installation. All choices can be found here:
+# http://www.i18nguy.com/unicode/language-identifiers.html
+LANGUAGE_CODE = 'en-us'
+
+SITE_ID = 1
+
+# If you set this to False, Django will make some optimizations so as not
+# to load the internationalization machinery.
+USE_I18N = True
+
+# Absolute path to the directory that holds media.
+# Example: "/home/media/media.lawrence.com/"
+MEDIA_ROOT = ''
+
+# URL that handles the media served from MEDIA_ROOT. Make sure to use a
+# trailing slash if there is a path component (optional in other cases).
+# Examples: "http://media.lawrence.com", "http://example.com/media/"
+MEDIA_URL = ''
+
+# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
+# trailing slash.
+# Examples: "http://foo.com/media/", "/media/".
+ADMIN_MEDIA_PREFIX = '/media/'
+
+# Make this unique, and don't share it with anybody.
+SECRET_KEY = '_+n^blk6hik*s1kfylp1pm8fpu9n0#=z_9cngayme5)-**$(#9'
+
+# List of callables that know how to import templates from various sources.
+TEMPLATE_LOADERS = (
+    'django.template.loaders.filesystem.load_template_source',
+    'django.template.loaders.app_directories.load_template_source',
+#     'django.template.loaders.eggs.load_template_source',
+)
+
+MIDDLEWARE_CLASSES = (
+    'django.middleware.common.CommonMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+)
+
+ROOT_URLCONF = 'pypy_demo.urls'
+
+TEMPLATE_DIRS = (
+    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
+    # Always use forward slashes, even on Windows.
+    # Don't forget to use absolute paths, not relative paths.
+)
+
+INSTALLED_APPS = (
+    ## 'django.contrib.auth',
+    ## 'django.contrib.contenttypes',
+    ## 'django.contrib.sessions',
+    ## 'django.contrib.sites',
+    'pypy_demo.manderlbrot',
+)

Added: pypy/extradoc/talk/pycon-italy-2010/pypy_demo/urls.py
==============================================================================
--- (empty file)
+++ pypy/extradoc/talk/pycon-italy-2010/pypy_demo/urls.py	Wed May  5 17:00:04 2010
@@ -0,0 +1,19 @@
+from django.conf.urls.defaults import *
+
+# Uncomment the next two lines to enable the admin:
+# from django.contrib import admin
+# admin.autodiscover()
+
+urlpatterns = patterns('',
+    # Example:
+    (r'^render$', 'pypy_demo.manderlbrot.views.render'),
+    (r'^pypy_render$', 'pypy_demo.manderlbrot.views.pypy_render'),
+    (r'^empty$', 'pypy_demo.manderlbrot.views.empty'),       
+
+    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
+    # to INSTALLED_APPS to enable admin documentation:
+    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
+
+    # Uncomment the next line to enable the admin:
+    # (r'^admin/', include(admin.site.urls)),
+)



More information about the Pypy-commit mailing list