
import myutil
import numpy as N
import copy
import itertools
import time as T
#from handythread import foreach
import multiprocessing
processes = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=processes)

def IPs():
    """Find inner products of all arrays with themselves"""
    arraySize = (3000,1000)
    numArrays = 50
    #arrayList = pool.map(myutil.my_random,itertools.repeat(arraySize,numArrays))
    arrayList = [N.random.random(s) for s in itertools.repeat(arraySize,numArrays)]
    IPs = N.zeros(numArrays)
    
    startTime = T.time()
    for arrayIndex,arrayValue in enumerate(arrayList):
        IPs[arrayIndex] = myutil.numpy_inner_product(arrayValue)
    endTime = T.time() - startTime
    print 'No shared memory, numpy array multiplication took',endTime,'seconds'
    
    startTime = T.time()
    innerProductList = pool.map(myutil.numpy_inner_product, arrayList)
    #innerProductList = \
    #    foreach(myutil.numpy_inner_product, arrayList, threads=8, return_=True)
    endTime = T.time() - startTime
    IPs = N.array(innerProductList)
    print 'Shared memory, numpy array multiplication took',endTime,'seconds'
    
    startTime = T.time()
    innerProductList = pool.map(myutil.numpy_inner_product, myutil.arrayList)
    #innerProductList = \
    #    foreach(myutil.numpy_inner_product, arrayList, threads=8, return_=True)
    endTime = T.time() - startTime
    IPs = N.array(innerProductList)
    print 'Shared memory, myutil.arrayList numpy array multiplication took',endTime,'seconds'
    
    """
    startTime = T.time()
    for arrayIndex,arrayValue in enumerate(arrayList):
        IPs[arrayIndex] = myutil.numexpr_inner_product(arrayValue)
    endTime = T.time() - startTime
    print 'No shared memory, numexpr array multiplication took',endTime,'seconds'
    
    startTime = T.time()
    innerProductList = pool.map(myutil.numexpr_inner_product, arrayList)
    #innerProductList = \
    #    foreach(myutil.numexpr_inner_product, arrayList, threads=16, return_=True)
    IPs = N.array(innerProductList)
    endTime = T.time() - startTime
    print 'Shared memory, numexpr array multiplication took',endTime,'seconds'
    
    
    startTime = T.time()
    for arrayIndex,arrayValue in enumerate(arrayList):
        IPs[arrayIndex] = myutil.my_inner_product(arrayValue)
    endTime = T.time() - startTime
    print 'No shared memory, my array multiplication took',endTime,'seconds'

    startTime = T.time()
    innerProductList = pool.map(myutil.my_inner_product, arrayList)
    IPs = N.array(innerProductList)
    endTime = T.time() - startTime
    print 'Shared memory, my array multiplication took',endTime,'seconds'
    """
    
if __name__ == '__main__':
    print 'Using',processes,'processes'
    IPs()

