can multi-core improve single funciton?

sturlamolden sturlamolden at yahoo.no
Wed Feb 18 20:36:25 EST 2009


On Feb 10, 7:28 am, oyster <lepto.pyt... at gmail.com> wrote:
> I mean this
> [code]
> def fib(n):
>     if n<=1:
>         return 1
>     return fib(n-1)+fib(n-2)


Let's rewrite that slightly and see...



def fib(n, _map=None):
    if not _map: _map = map
    if n > 2:
        return sum(_map(fib, (n-1, n-2)))
    else:
        return 1


if __name__ == '__main__':

    from multiprocessing import Pool
    from time import clock

    p = Pool()
    n = 36

    t0 = clock()
    fib(n, p.map)
    t1 = clock()

    print 'parallel t: %f seconds' % (t1-t0)

    t0 = clock()
    fib(n)
    t1 = clock()

    print 'sequential t: %f seconds' % (t1-t0)


With two cores:

E:\>python fibotest.py
parallel t: 31.300226 seconds
sequential t: 48.070695 seconds


Yes it can!




Sturla Molden



More information about the Python-list mailing list