Skip to content

Instantly share code, notes, and snippets.

@robbyt
Created March 30, 2012 18:44
Show Gist options
  • Save robbyt/2253894 to your computer and use it in GitHub Desktop.
Save robbyt/2253894 to your computer and use it in GitHub Desktop.
Fun with cache locality and pypy

Intro

I wrote a program in Python called mew.

#!/usr/bin/env python

def mew(l, n, m):
    """ l = list of ints
        n = number of list members to skip
        m = multiplier 
    """
    for i in range(0, len(l), n):
        l[i] = l[i] * m
    return l

def main(args):
    d = mew(range(int(args[1])), int(args[2]), int(args[3]))
    print sum(d)
    return 0

if __name__ == "__main__":
    import sys
    main(sys.argv)

It takes a big number, the first argument, creates a list, then it multiplies (argv[3]) every n'th (argv[2]) number. Finally it sums the resulting list.

(v_csh)(master)rtmp:mew rterhaar$ time ./mew.py 134217728 16 3
10133098960257024

real 0m8.490s
user 0m6.299s
sys 0m2.189s

However if I make a couple of minor modifications and then compile that code with pypy:

#!/usr/bin/env python

def mew(l, n, m):
    """ l = list of ints
        n = number of list members to skip
        m = multiplier 
    """
    for i in range(0, len(l), n):
        l[i] = l[i] * m
    return l

def summer(l):
    """ Pypy does not support sum()
    """
    ans = 0
    for i in l:
        ans += i
    return ans

def main(args):
    d = mew(range(int(args[1])), int(args[2]), int(args[3]))
    print summer(d)
    return 0

def target(*args):
    return main, None

if __name__ == "__main__":
    import sys
    main(sys.argv)
(v_csh)(master)rtmp:mew rterhaar$ time ./mew-c 134217728 16 3
10133098960257024

real 0m0.821s
user 0m0.451s
sys 0m0.351s

it takes .8 seconds

@j2labs
Copy link

j2labs commented Mar 30, 2012

Wow. Pypy owned that comparison.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment