import numpy
from multiprocessing import Pool
from time import time
import subprocess, os, sys

N = 1000*1000*10
expr = "a + b*x + c*x**2 + d*x**3 + e*x**4"
a, b, c, d, e = -1.1, 2.2, -3.3, 4.4, -5.5
xp = numpy.linspace(-1, 1, N)

parallel = True
NT = 3

global counter
counter = 0
def cb(r):
    global counter
    print r, counter
    counter +=1

def compute(nt, i):
    x = xp[i*N/nt:(i+1)*N/nt]
    eval(expr)
    return len(x)


if __name__ == '__main__':

    print "Serial computation..."
    t0 = time()
    result = compute(1,0)
    print result, 0
    ts = round(time() - t0, 3)
    print "Time elapsed in serial computation:", ts

    if not parallel:
        sys.exit()

    t0 = time()
    po = Pool(processes=NT)
    for i in xrange(NT):
        po.apply_async(compute, (NT,i), callback=cb)
    po.close()
    po.join()
    tp = round(time() - t0, 3)
    print "Time elapsed in parallel computation:", tp, "with %s threads" % NT

    print "Speed-up: %sx" % round(ts/tp, 2)
