#!/usr/bin/python
# The script was taken from the intel web-site and modified
# https://software.intel.com/sites/default/files/0f/a7/mkl_benchmark.py
import os
import sys
import timeit
import numpy
from numpy.random import random
 
def test_eigenvalue():
     """ Test eigen value computation of a matrix """
     i = 500
     data = random((i,i))
     result = numpy.linalg.eig(data)
 
def test_svd():
     """ Test single value decomposition of a matrix """
     i = 1000
     data = random((i,i))
     result = numpy.linalg.svd(data)
     result = numpy.linalg.svd(data, full_matrices=False)
 
def test_inv():
     """ Test matrix inversion """
     i = 1000
     data = random((i,i))
     result = numpy.linalg.inv(data)
 
def test_det():
     """ Test the computation of the matrix determinant """
     i = 1000
     data = random((i,i))
     result = numpy.linalg.det(data)
 
def test_dot():
     """ Test the dot product """
     i = 1000
     a = random((i, i))
     b = numpy.linalg.inv(a)
     result = numpy.dot(a, b) - numpy.eye(i)
 
# Test to start. The dict is the value I had with the WEBER with MKL followed by Strauss with MKL
tests = {test_eigenvalue : (349., 182.5),
test_svd : (1948.7, 1179.3),
test_inv : (175.3, 134.2),
test_det : (61.7, 40.8),
test_dot : (270.1, 146.6) }
 
# Setting the following environment variable in the shell executing the script allows
# you limit the maximal number threads used for computation
THREADS_LIMIT_ENV = 'MKL_NUM_THREADS'
 
def start_benchmark():
    print("""Benchmark is made against Weber with MKL and Strauss with MKL running single threaded""")
    if THREADS_LIMIT_ENV in os.environ:
        print("Maximum number of threads used for computation is : %s" % os.environ[THREADS_LIMIT_ENV])
    numpy.seterr(all='ignore')
    print(("-" * 80))
    print("Starting timing with numpy %s\nVersion: %s" % (numpy.__version__, sys.version))
    print("%20s : %10s - %5s / %5s" % ("Function", "Timing [ms]", "Weber", "Strauss"))
    for fun, bench in tests.items():
        t = timeit.Timer(stmt="%s()" % fun.__name__, setup="from __main__ import %s" % fun.__name__)
        res = t.repeat(repeat=6, number=1)
        timing = 1000.0 * sum(res)/len(res)
        print("%20s : %7.1f ms - %3.2f / %3.2f" % (fun.__name__, timing, bench[0]/timing, bench[1]/timing))
 
if __name__ == '__main__':
    start_benchmark()
