Author: Matti Picus <[email protected]>
Branch: chameleon
Changeset: r397:9e289c136648
Date: 2020-01-01 12:13 +0200
http://bitbucket.org/pypy/benchmarks/changeset/9e289c136648/

Log:    merge py3 into branch, update own/*.py for python3

diff --git a/.hgignore b/.hgignore
--- a/.hgignore
+++ b/.hgignore
@@ -1,3 +1,4 @@
 .*\.py[co]
 .*~
 lib/cpython-doc/tools/build
+.*.swp
diff --git a/benchmarks.py b/benchmarks.py
--- a/benchmarks.py
+++ b/benchmarks.py
@@ -1,4 +1,7 @@
+from __future__ import division, print_function
+
 import os
+import sys
 import logging
 from unladen_swallow.perf import SimpleBenchmark, MeasureGeneric
 from unladen_swallow.perf import RawResult, SimpleComparisonResult, avg, 
ResultError
@@ -48,7 +51,7 @@
         try:
             base_data = benchmark_function(base_python, options,
                                            *args, **kwargs)
-        except subprocess.CalledProcessError, e:
+        except subprocess.CalledProcessError as e:
             return ResultError(e)
         return SimpleComparisonResult(avg(base_data[0]), -1, -1)
     BM.func_name = 'BM_' + bm_name
@@ -90,11 +93,16 @@
              'spectral-norm', 'chaos', 'telco', 'go', 'pyflate-fast',
              'raytrace-simple', 'crypto_pyaes', 'bm_mako', 'bm_chameleon',
              'json_bench', 'pidigits', 'hexiom2', 'eparse', 'deltablue',
-             'bm_dulwich_log', 'bm_krakatau', 'bm_mdp', 'pypy_interp',
+             'bm_dulwich_log', 'bm_mdp', 'pypy_interp',
              'sqlitesynth', 'pyxl_bench', 'nqueens', 'sqlalchemy_declarative',
              'sqlalchemy_imperative']:
     _register_new_bm(name, name, globals(), **opts.get(name, {}))
 
+if sys.version_info[0] < 3:
+    # does not support python 3
+    for name in ['bm_krakatau',]:
+        _register_new_bm(name, name, globals(), **opts.get(name, {}))
+
 for name in ['names', 'iteration', 'tcp', 'pb', ]:#'web']:#, 'accepts']:
     if name == 'web':
         iteration_scaling = 0.2
@@ -173,11 +181,11 @@
     retcode = proc.poll()
     if retcode != 0:
         if out is not None:
-            print '---------- stdout ----------'
-            print out
+            print('---------- stdout ----------')
+            print(out)
         if err is not None:
-            print '---------- stderr ----------'
-            print err
+            print('---------- stderr ----------')
+            print(err)
         raise Exception("translate.py failed, retcode %r" % (retcode,))
 
     lines = err.splitlines()
@@ -213,8 +221,8 @@
         out, err = proc.communicate()
         retcode = proc.poll()
         if retcode != 0:
-            print out
-            print err
+            print(out)
+            print(err)
             raise Exception("sphinx-build.py failed")
         t.append(float(out.splitlines()[-1]))
     return RawResult([t[0]], [t[1]])
diff --git a/own/bm_chameleon.py b/own/bm_chameleon.py
--- a/own/bm_chameleon.py
+++ b/own/bm_chameleon.py
@@ -1,5 +1,10 @@
 
 from chameleon import PageTemplate
+import sys
+if sys.version_info[0] < 3:
+    strstr = 'unicode'
+else:
+    strstr = 'str'
 
 BIGTABLE_ZPT = """\
 <table xmlns="http://www.w3.org/1999/xhtml";
@@ -7,11 +12,11 @@
 <tr tal:repeat="row python: options['table']">
 <td tal:repeat="c python: row.values()">
 <span tal:define="d python: c + 1"
-tal:attributes="class python: 'column-' + unicode(d)"
+tal:attributes="class python: 'column-' + %s(d)"
 tal:content="python: d" />
 </td>
 </tr>
-</table>"""
+</table>""" % strstr
 
 def main(n):
     tmpl = PageTemplate(BIGTABLE_ZPT)
diff --git a/own/bm_dulwich_log.py b/own/bm_dulwich_log.py
--- a/own/bm_dulwich_log.py
+++ b/own/bm_dulwich_log.py
@@ -10,7 +10,7 @@
     import time
     for i in range(20):
         t0 = time.time()
-        r.revision_history(r.head())
+        [e.commit for e in r.get_walker(r.head())]
         l.append(time.time() - t0)
     return l
 
diff --git a/own/bm_mako.py b/own/bm_mako.py
--- a/own/bm_mako.py
+++ b/own/bm_mako.py
@@ -17,6 +17,12 @@
 import optparse
 import time
 
+if sys.version_info[0] < 3:
+    rangestr = 'xrange'
+else:
+    xrange = range
+    rangestr = 'range'
+
 # Local imports
 import util
 
@@ -64,25 +70,25 @@
 """
 
 PAGE_TEMPLATE = """
-<%inherit file="base.mako"/>
+<%%inherit file="base.mako"/>
 <table>
-    % for row in table:
+    %% for row in table:
         <tr>
-            % for col in row:
+            %% for col in row:
                 <td>${col}</td>
-            % endfor
+            %% endfor
         </tr>
-    % endfor
+    %% endfor
 </table>
-% for nr in xrange(img_count):
+%% for nr in %s(img_count):
     ${parent.img('/foo/bar/baz.png', 'no image :o')}
-% endfor
+%% endfor
 ${next.body()}
-% for nr in paragraphs:
+%% for nr in paragraphs:
     <p>${lorem|x}</p>
-% endfor
+%% endfor
 ${parent.render_table(table)}
-"""
+""" % rangestr
 
 CONTENT_TEMPLATE = """
 <%inherit file="page.mako"/>
diff --git a/own/bm_mdp.py b/own/bm_mdp.py
--- a/own/bm_mdp.py
+++ b/own/bm_mdp.py
@@ -243,7 +243,7 @@
                        return []
                temp = self.getSuccessors(statep)
                if statep[0] != 0:
-                       temp = zip(*temp)[0] if temp else []
+                       temp = list(zip(*temp))[0] if temp else []
                return temp
 
        def evaluate(self, tolerance=0.15):
@@ -262,7 +262,7 @@
                itercount = 0
                while dmax[initial_statep] - dmin[initial_statep] > tolerance:
                        itercount += 1
-                       #print itercount, dmax[initial_statep] - 
dmin[initial_statep], len(frozen)
+                       #print(itercount, dmax[initial_statep] - 
dmin[initial_statep], len(frozen))
 
                        for sp in stateps:
                                if sp in frozen:
diff --git a/own/chaos.py b/own/chaos.py
--- a/own/chaos.py
+++ b/own/chaos.py
@@ -12,6 +12,9 @@
 random.seed(1234)
 import sys
 import time
+if sys.version_info[0] > 2:
+    from functools import reduce
+    xrange = range
 
 class GVector(object):
     def __init__(self, x = 0, y = 0, z = 0):
@@ -29,8 +32,7 @@
 
     def __add__(self, other):
         if not isinstance(other, GVector):
-            raise ValueError, \
-                    "Can't add GVector to " + str(type(other))
+            raise ValueError( "Can't add GVector to " + str(type(other)))
         v = GVector(self.x + other.x, self.y + other.y, self.z + other.z)
         return v
 
@@ -71,14 +73,13 @@
             self.knots = GetKnots(points, degree)
         else:
             if len(points) > len(knots) - degree + 1:
-                raise ValueError, "too many control points"
+                raise ValueError("too many control points")
             elif len(points) < len(knots) - degree + 1:
-                raise ValueError, "not enough control points"
+                raise ValueError("not enough control points")
             last = knots[0]
             for cur in knots[1:]:
                 if cur < last:
-                    raise ValueError, \
-                          "knots not strictly increasing"
+                    raise ValueError("knots not strictly increasing")
                 last = cur
             self.knots = knots
         self.points = points
@@ -93,7 +94,7 @@
         """Calculates a point of the B-Spline using de Boors Algorithm"""
         dom = self.GetDomain()
         if u < dom[0] or u > dom[1]:
-            raise ValueError, "Function value not in domain"
+            raise ValueError("Function value not in domain")
         if u == dom[0]:
             return self.points[0]
         if u == dom[1]:
@@ -131,17 +132,17 @@
         
 def save_im(im, fn):
     f = open(fn, "wb")
-    magic = 'P6\n'
+    magic = b'P6\n'
     maxval = 255
     w = len(im)
     h = len(im[0])
     f.write(magic)
-    f.write('%i %i\n%i\n' % (w, h, maxval))
+    f.write(b'%i %i\n%i\n' % (w, h, maxval))
     for j in range(h):
         for i in range(w):
             val = im[i][j]
             c = val * 255
-            f.write('%c%c%c' % (c, c, c))
+            f.write(b'%c%c%c' % (c, c, c))
     f.close()
 
 class Chaosgame(object):
@@ -199,7 +200,7 @@
             basepoint.y += -derivative.x / derivative.Mag() * (y - 0.5) * \
                            self.thickness
         else:
-            print "r",
+            print("r", end='')
         self.truncate(basepoint)
         return basepoint
 
diff --git a/own/crypto_pyaes.py b/own/crypto_pyaes.py
--- a/own/crypto_pyaes.py
+++ b/own/crypto_pyaes.py
@@ -3,15 +3,19 @@
 import util
 import optparse
 import time
+import sys
+import codecs
+if sys.version_info[0] > 2:
+    xrange = range
 
 import pyaes
 
-cleartext = "This is a test. What could possibly go wrong? " * 2000 # 92000 
bytes
+cleartext = b"This is a test. What could possibly go wrong? " * 2000 # 92000 
bytes
 
 def benchmark():
     # 128-bit key
-    key = 'a1f6258c877d5fcd8964484538bfc92c'.decode('hex')
-    iv  = 'ed62e16363638360fdd6ad62112794f0'.decode('hex')
+    key = codecs.decode(b'a1f6258c877d5fcd8964484538bfc92c', 'hex')
+    iv  = codecs.decode(b'ed62e16363638360fdd6ad62112794f0', 'hex')
 
     aes = pyaes.new(key, pyaes.MODE_CBC, iv)
     ciphertext = aes.encrypt(cleartext)
diff --git a/own/pyaes.py b/own/pyaes.py
--- a/own/pyaes.py
+++ b/own/pyaes.py
@@ -49,6 +49,10 @@
 
 
 from array import array
+import sys
+import codecs
+if sys.version_info[0] > 2:
+    xrange = range
 
 # Globals mandated by PEP 272:
 # http://www.python.org/dev/peps/pep-0272/
@@ -64,7 +68,7 @@
         return ECBMode(AES(key))
     elif mode == MODE_CBC:
         if IV is None:
-            raise ValueError, "CBC mode needs an IV value!"
+            raise ValueError("CBC mode needs an IV value!")
 
         return CBCMode(AES(key), IV)
     else:
@@ -91,7 +95,7 @@
         elif self.key_size == 32:
             self.rounds = 14
         else:
-            raise ValueError, "Key length must be 16, 24 or 32 bytes"
+            raise ValueError("Key length must be 16, 24 or 32 bytes")
 
         self.expand_key()
 
@@ -169,7 +173,7 @@
         for i in xrange(16):
             block[i] ^= exkey[offset + i]
 
-        #print 'AddRoundKey:', block
+        #print('AddRoundKey:', block)
 
     def sub_bytes(self, block, sbox):
         """SubBytes step, apply S-box to all bytes
@@ -181,7 +185,7 @@
         for i in xrange(16):
             block[i] = sbox[block[i]]
 
-        #print 'SubBytes   :', block
+        #print('SubBytes   :', block)
 
     def shift_rows(self, b):
         """ShiftRows step. Shifts 2nd row to left by 1, 3rd row by 2, 4th row 
by 3
@@ -199,7 +203,7 @@
         b[2], b[6], b[10], b[14] = b[10], b[14], b[ 2], b[ 6]
         b[3], b[7], b[11], b[15] = b[15], b[ 3], b[ 7], b[11]
 
-        #print 'ShiftRows  :', b
+        #print('ShiftRows  :', b)
 
     def shift_rows_inv(self, b):
         """Similar to shift_rows above, but performed in inverse for 
decryption."""
@@ -208,7 +212,7 @@
         b[10], b[14], b[ 2], b[ 6] = b[2], b[6], b[10], b[14]
         b[15], b[ 3], b[ 7], b[11] = b[3], b[7], b[11], b[15]
 
-        #print 'ShiftRows  :', b
+        #print('ShiftRows  :', b)
 
     def mix_columns(self, block):
         """MixColumns step. Mixes the values in each column"""
@@ -231,7 +235,7 @@
             block[col+2] = mul_by_2[v2] ^ v1 ^ v0 ^ mul_by_3[v3]
             block[col+3] = mul_by_2[v3] ^ v2 ^ v1 ^ mul_by_3[v0]
 
-        #print 'MixColumns :', block
+        #print('MixColumns :', block)
 
     def mix_columns_inv(self, block):
         """Similar to mix_columns above, but performed in inverse for 
decryption."""
@@ -256,7 +260,7 @@
             block[col+2] = mul_14[v2] ^ mul_9[v1] ^ mul_13[v0] ^ mul_11[v3]
             block[col+3] = mul_14[v3] ^ mul_9[v2] ^ mul_13[v1] ^ mul_11[v0]
 
-        #print 'MixColumns :', block
+        #print('MixColumns :', block)
 
     def encrypt_block(self, block):
         """Encrypts a single block. This is the main AES function"""
@@ -313,7 +317,7 @@
         """Perform ECB mode with the given function"""
 
         if len(data) % self.block_size != 0:
-            raise ValueError, "Plaintext length must be multiple of 16"
+            raise ValueError("Plaintext length must be multiple of 16")
 
         block_size = self.block_size
         data = array('B', data)
@@ -357,7 +361,7 @@
 
         block_size = self.block_size
         if len(data) % block_size != 0:
-            raise ValueError, "Plaintext length must be multiple of 16"
+            raise ValueError("Plaintext length must be multiple of 16")
 
         data = array('B', data)
         IV = self.IV
@@ -381,7 +385,7 @@
 
         block_size = self.block_size
         if len(data) % block_size != 0:
-            raise ValueError, "Ciphertext length must be multiple of 16"
+            raise ValueError("Ciphertext length must be multiple of 16")
 
         data = array('B', data)
         IV = self.IV
@@ -436,45 +440,45 @@
 #
 # More information: http://en.wikipedia.org/wiki/Rijndael_S-box
 
-aes_sbox = array('B',
-    '637c777bf26b6fc53001672bfed7ab76'
-    'ca82c97dfa5947f0add4a2af9ca472c0'
-    'b7fd9326363ff7cc34a5e5f171d83115'
-    '04c723c31896059a071280e2eb27b275'
-    '09832c1a1b6e5aa0523bd6b329e32f84'
-    '53d100ed20fcb15b6acbbe394a4c58cf'
-    'd0efaafb434d338545f9027f503c9fa8'
-    '51a3408f929d38f5bcb6da2110fff3d2'
-    'cd0c13ec5f974417c4a77e3d645d1973'
-    '60814fdc222a908846eeb814de5e0bdb'
-    'e0323a0a4906245cc2d3ac629195e479'
-    'e7c8376d8dd54ea96c56f4ea657aae08'
-    'ba78252e1ca6b4c6e8dd741f4bbd8b8a'
-    '703eb5664803f60e613557b986c11d9e'
-    'e1f8981169d98e949b1e87e9ce5528df'
-    '8ca1890dbfe6426841992d0fb054bb16'.decode('hex')
+aes_sbox = array('B', codecs.decode(
+    b'637c777bf26b6fc53001672bfed7ab76'
+    b'ca82c97dfa5947f0add4a2af9ca472c0'
+    b'b7fd9326363ff7cc34a5e5f171d83115'
+    b'04c723c31896059a071280e2eb27b275'
+    b'09832c1a1b6e5aa0523bd6b329e32f84'
+    b'53d100ed20fcb15b6acbbe394a4c58cf'
+    b'd0efaafb434d338545f9027f503c9fa8'
+    b'51a3408f929d38f5bcb6da2110fff3d2'
+    b'cd0c13ec5f974417c4a77e3d645d1973'
+    b'60814fdc222a908846eeb814de5e0bdb'
+    b'e0323a0a4906245cc2d3ac629195e479'
+    b'e7c8376d8dd54ea96c56f4ea657aae08'
+    b'ba78252e1ca6b4c6e8dd741f4bbd8b8a'
+    b'703eb5664803f60e613557b986c11d9e'
+    b'e1f8981169d98e949b1e87e9ce5528df'
+    b'8ca1890dbfe6426841992d0fb054bb16', 'hex')
 )
 
 # This is the inverse of the above. In other words:
 # aes_inv_sbox[aes_sbox[val]] == val
 
-aes_inv_sbox = array('B',
-    '52096ad53036a538bf40a39e81f3d7fb'
-    '7ce339829b2fff87348e4344c4dee9cb'
-    '547b9432a6c2233dee4c950b42fac34e'
-    '082ea16628d924b2765ba2496d8bd125'
-    '72f8f66486689816d4a45ccc5d65b692'
-    '6c704850fdedb9da5e154657a78d9d84'
-    '90d8ab008cbcd30af7e45805b8b34506'
-    'd02c1e8fca3f0f02c1afbd0301138a6b'
-    '3a9111414f67dcea97f2cfcef0b4e673'
-    '96ac7422e7ad3585e2f937e81c75df6e'
-    '47f11a711d29c5896fb7620eaa18be1b'
-    'fc563e4bc6d279209adbc0fe78cd5af4'
-    '1fdda8338807c731b11210592780ec5f'
-    '60517fa919b54a0d2de57a9f93c99cef'
-    'a0e03b4dae2af5b0c8ebbb3c83539961'
-    '172b047eba77d626e169146355210c7d'.decode('hex')
+aes_inv_sbox = array('B', codecs.decode(
+    b'52096ad53036a538bf40a39e81f3d7fb'
+    b'7ce339829b2fff87348e4344c4dee9cb'
+    b'547b9432a6c2233dee4c950b42fac34e'
+    b'082ea16628d924b2765ba2496d8bd125'
+    b'72f8f66486689816d4a45ccc5d65b692'
+    b'6c704850fdedb9da5e154657a78d9d84'
+    b'90d8ab008cbcd30af7e45805b8b34506'
+    b'd02c1e8fca3f0f02c1afbd0301138a6b'
+    b'3a9111414f67dcea97f2cfcef0b4e673'
+    b'96ac7422e7ad3585e2f937e81c75df6e'
+    b'47f11a711d29c5896fb7620eaa18be1b'
+    b'fc563e4bc6d279209adbc0fe78cd5af4'
+    b'1fdda8338807c731b11210592780ec5f'
+    b'60517fa919b54a0d2de57a9f93c99cef'
+    b'a0e03b4dae2af5b0c8ebbb3c83539961'
+    b'172b047eba77d626e169146355210c7d', 'hex')
 )
 
 # The Rcon table is used in AES's key schedule (key expansion)
@@ -482,21 +486,21 @@
 #
 # More information: http://en.wikipedia.org/wiki/Rijndael_key_schedule
 
-aes_Rcon = array('B',
-    '8d01020408102040801b366cd8ab4d9a'
-    '2f5ebc63c697356ad4b37dfaefc59139'
-    '72e4d3bd61c29f254a943366cc831d3a'
-    '74e8cb8d01020408102040801b366cd8'
-    'ab4d9a2f5ebc63c697356ad4b37dfaef'
-    'c5913972e4d3bd61c29f254a943366cc'
-    '831d3a74e8cb8d01020408102040801b'
-    '366cd8ab4d9a2f5ebc63c697356ad4b3'
-    '7dfaefc5913972e4d3bd61c29f254a94'
-    '3366cc831d3a74e8cb8d010204081020'
-    '40801b366cd8ab4d9a2f5ebc63c69735'
-    '6ad4b37dfaefc5913972e4d3bd61c29f'
-    '254a943366cc831d3a74e8cb8d010204'
-    '08102040801b366cd8ab4d9a2f5ebc63'
-    'c697356ad4b37dfaefc5913972e4d3bd'
-    '61c29f254a943366cc831d3a74e8cb'.decode('hex')
+aes_Rcon = array('B', codecs.decode(
+    b'8d01020408102040801b366cd8ab4d9a'
+    b'2f5ebc63c697356ad4b37dfaefc59139'
+    b'72e4d3bd61c29f254a943366cc831d3a'
+    b'74e8cb8d01020408102040801b366cd8'
+    b'ab4d9a2f5ebc63c697356ad4b37dfaef'
+    b'c5913972e4d3bd61c29f254a943366cc'
+    b'831d3a74e8cb8d01020408102040801b'
+    b'366cd8ab4d9a2f5ebc63c697356ad4b3'
+    b'7dfaefc5913972e4d3bd61c29f254a94'
+    b'3366cc831d3a74e8cb8d010204081020'
+    b'40801b366cd8ab4d9a2f5ebc63c69735'
+    b'6ad4b37dfaefc5913972e4d3bd61c29f'
+    b'254a943366cc831d3a74e8cb8d010204'
+    b'08102040801b366cd8ab4d9a2f5ebc63'
+    b'c697356ad4b37dfaefc5913972e4d3bd'
+    b'61c29f254a943366cc831d3a74e8cb', 'hex')
 )
diff --git a/own/util.py b/own/util.py
--- a/own/util.py
+++ b/own/util.py
@@ -2,4 +2,5 @@
 
 root = os.path.abspath(os.path.join(__file__, '..', '..'))
 util_py = os.path.join(root, 'unladen_swallow', 'performance', 'util.py')
-execfile(util_py)
+with open(util_py) as fid:
+    exec(fid.read())
diff --git a/runner.py b/runner.py
--- a/runner.py
+++ b/runner.py
@@ -1,6 +1,7 @@
 #!/usr/bin/env python
 """ Usage: runner.py <result filename> <path to pypy-c> <revnumber>
 """
+from __future__ import division, print_function
 
 import json
 import socket
@@ -316,8 +317,8 @@
             # prevent to upload results from the nullpython dummy
             host = force_host if force_host else socket.gethostname()
             for url in urls:
-                print save(project, revision, results, executable, host, url,
-                           changed=(run == CHANGED), branch=branch)
+                print(save(project, revision, results, executable, host, url,
+                           changed=(run == CHANGED), branch=branch))
 
 
 if __name__ == '__main__':
diff --git a/saveresults.py b/saveresults.py
--- a/saveresults.py
+++ b/saveresults.py
@@ -20,13 +20,17 @@
   $ ./saveresults.py result.json -r '45757:fabe4fc0dc08' -n pypy-c-jit-64 \
     -H tannit
 """
+from __future__ import division, print_function
 
 from datetime import datetime
 import optparse
 import sys
 import time
 import urllib
-import urllib2
+try:
+    import urllib2
+except ImportError:
+    import urllib.request as urllib2
 import json
 
 
@@ -73,7 +77,7 @@
             'branch': branch,
         }]
         if value is None:
-            print "Ignoring skipped result", data
+            print("Ignoring skipped result", data)
             continue
         if res_type == "ComparisonResult":
             if changed:
@@ -117,9 +121,9 @@
                 if not retries:
                     raise
                 d = retries.pop(0)
-                print "retrying in %d seconds..." % d
+                print("retrying in %d seconds..." % d)
                 time.sleep(d)
-    except urllib2.URLError, e:
+    except urllib2.URLError as e:
         if hasattr(e, 'reason'):
             response = '\n  We failed to reach a server\n'
             response += '  Reason: ' + str(e.reason)
@@ -127,13 +131,13 @@
             response = '\n  The server couldn\'t fulfill the request'
         if hasattr(e, 'readlines'):
             response = "".join([response] + e.readlines())
-        print response
+        print(response)
         with open('error.html', 'w') as error_file:
             error_file.write(response)
         print("Server (%s) response written to error.html" % (url,))
         print('  Error code: %s\n' % (e,))
         return 1
-    print "saved correctly!\n"
+    print("saved correctly!", end='\n\n')
     return 0
 
 
@@ -142,10 +146,10 @@
     with open(jsonfile) as f:
         data = simplejson.load(f)
     results = data['results']
-    print 'uploading results...',
+    print('uploading results...', end='')
     save(options.project, options.revision, results, options.executable,
                 options.host, options.url, changed=options.changed)
-    print 'done'
+    print('done')
 
 
 if __name__ == '__main__':
diff --git a/unladen_swallow/perf.py b/unladen_swallow/perf.py
--- a/unladen_swallow/perf.py
+++ b/unladen_swallow/perf.py
@@ -44,7 +44,7 @@
   changed_python -A -B the_benchmark.py
 """
 
-from __future__ import division, with_statement
+from __future__ import division, print_function
 
 __author__ = "[email protected] (Jeffrey Yasskin)"
 
@@ -62,7 +62,10 @@
 import tempfile
 import time
 import threading
-import urllib2
+try:
+    import urllib2
+except ImportError:
+    import urllib.request as urllib2
 try:
     import multiprocessing
 except ImportError:
@@ -301,7 +304,7 @@
         future = MemoryUsageFuture(some_pid)
         ...
         usage = future.GetMemoryUsage()
-        print max(usage)
+        print(max(usage))
 
     Note that calls to GetMemoryUsage() will block until the process exits.
     """
@@ -459,7 +462,7 @@
                                           *args, **kwargs)
         base_data = benchmark_function(base_python, options,
                                        *args, **kwargs)
-    except subprocess.CalledProcessError, e:
+    except subprocess.CalledProcessError as e:
         return ResultError(e)
 
     return CompareBenchmarkData(base_data, changed_data, options)
@@ -588,9 +591,9 @@
 
 
 def LogCall(command):
-    command = map(str, command)
-    info("Running %s", " ".join(command))
-    return command
+    cmd = list(map(str, command))
+    info("Running %s", " ".join(cmd))
+    return cmd
 
 
 try:
@@ -672,12 +675,12 @@
         human consumption.
     """
     if len(base_times) != len(changed_times):
-        print "Base:"
-        print base_times
-        print "Changed:"
-        print changed_times
+        print("Base:")
+        print(base_times)
+        print("Changed:")
+        print(changed_times)
         # XXX <arigo> hacked.  Got this error *once*, don't want to care
-        print "WARNING: length did not match"
+        print("WARNING: length did not match")
         l = min(len(base_times), len(changed_times))
         base_times = base_times[:l]
         changed_times = changed_times[:l]
@@ -770,7 +773,7 @@
         future = MemoryUsageFuture(subproc.pid)
     result, err = subproc.communicate()
     if subproc.returncode != 0:
-        print result
+        print(result)
         raise RuntimeError("Benchmark died (returncode: %d): %s" %
                            (subproc.returncode, err))
     if track_memory:
@@ -887,7 +890,7 @@
             result, err = comparer.communicate()
             if comparer.returncode != 0:
                 return "pybench died: " + err
-    except subprocess.CalledProcessError, e:
+    except subprocess.CalledProcessError as e:
         return str(e)
 
     if options.verbose:
@@ -1091,7 +1094,7 @@
                                        spitfire_env, extra_args)
         base_data = MeasureSpitfire(base_python, options,
                                     spitfire_env, extra_args)
-    except subprocess.CalledProcessError, e:
+    except subprocess.CalledProcessError as e:
         return str(e)
 
     return CompareBenchmarkData(base_data, changed_data, options)
@@ -1448,7 +1451,7 @@
 
 def _FindAllBenchmarks(namespace):
     return dict((name[3:].lower(), func)
-                for (name, func) in sorted(namespace.iteritems())
+                for (name, func) in sorted(namespace.items())
                 if name.startswith("BM_"))
 
 BENCH_FUNCS = _FindAllBenchmarks(globals())
@@ -1548,7 +1551,7 @@
 
 def main(argv, bench_funcs=BENCH_FUNCS, bench_groups=BENCH_GROUPS):
     bench_groups = bench_groups.copy()
-    all_benchmarks = bench_funcs.keys()
+    all_benchmarks = list(bench_funcs.keys())
     bench_groups["all"] = all_benchmarks
 
     parser = optparse.OptionParser(
@@ -1580,7 +1583,7 @@
                             " benchmarks except the negative arguments. " +
                             " Otherwise we run only the positive arguments. " +
                             " Valid benchmarks are: " +
-                            ", ".join(bench_groups.keys() + all_benchmarks)))
+                            ", ".join(list(bench_groups.keys()) + 
all_benchmarks)))
     parser.add_option("--inherit_env", metavar="ENVVARS", type="string", 
action="callback",
                       callback=ParseEnvVars, default=[],
                       help=("Comma-separated list of environment variable 
names"
@@ -1618,7 +1621,7 @@
     results = []
     for name in sorted(should_run):
         func = bench_funcs[name]
-        print "Running %s..." % name
+        print("Running %s..." % name)
         # PyPy specific modification: let the func to return a list of results
         # for sub-benchmarks
         bench_result = func(base_cmd_prefix, changed_cmd_prefix, options)
@@ -1631,13 +1634,13 @@
             results.append((name, bench_result))
 
     print
-    print "Report on %s" % " ".join(platform.uname())
+    print("Report on %s" % " ".join(platform.uname()))
     if multiprocessing:
-        print "Total CPU cores:", multiprocessing.cpu_count()
+        print("Total CPU cores:", multiprocessing.cpu_count())
     for name, result in results:
-        print
-        print "###", name, "###"
-        print result.string_representation()
+        print()
+        print("###", name, "###")
+        print(result.string_representation())
     return results
 
 if __name__ == "__main__":
diff --git a/unladen_swallow/performance/bm_ai.py 
b/unladen_swallow/performance/bm_ai.py
--- a/unladen_swallow/performance/bm_ai.py
+++ b/unladen_swallow/performance/bm_ai.py
@@ -10,7 +10,7 @@
 """
 
 # Wanted by the alphametics solver.
-from __future__ import division
+from __future__ import division, print_function
 
 __author__ = "[email protected] (Collin Winter)"
 
@@ -19,11 +19,16 @@
 import re
 import string
 import time
+import sys
+
+if sys.version_info[1] < 3:
+    range = xrange
 
 # Local imports
 import util
 
 
+
 # Pure-Python implementation of itertools.permutations().
 def permutations(iterable, r=None):
     """permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)"""
@@ -31,8 +36,8 @@
     n = len(pool)
     if r is None:
         r = n
-    indices = range(n)
-    cycles = range(n-r+1, n+1)[::-1]
+    indices = list(range(n))
+    cycles = list(range(n-r+1, n+1)[::-1])
     yield tuple(pool[i] for i in indices[:r])
     while n:
         for i in reversed(range(r)):
@@ -75,7 +80,7 @@
     list(n_queens(8))
 
     times = []
-    for _ in xrange(iterations):
+    for _ in range(iterations):
         t0 = time.time()
         list(n_queens(8))
         t1 = time.time()
diff --git a/unladen_swallow/performance/util.py 
b/unladen_swallow/performance/util.py
--- a/unladen_swallow/performance/util.py
+++ b/unladen_swallow/performance/util.py
@@ -1,6 +1,7 @@
 #!/usr/bin/env python
 
 """Utility code for benchmark scripts."""
+from __future__ import division, print_function
 
 __author__ = "[email protected] (Collin Winter)"
 
@@ -27,10 +28,10 @@
         data = bench_func(num_runs, *args)
         if options.take_geo_mean:
             product = reduce(operator.mul, data, 1)
-            print math.pow(product, 1.0 / len(data))
+            print(math.pow(product, 1.0 / len(data)))
         else:
             for x in data:
-                print x
+                print(x)
 
 
 def add_standard_options_to(parser):
_______________________________________________
pypy-commit mailing list
[email protected]
https://mail.python.org/mailman/listinfo/pypy-commit

Reply via email to