File: benchmark.py

package info (click to toggle)
tinyarray 1.2.3-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 276 kB
  • sloc: cpp: 2,805; python: 656; makefile: 12
file content (78 lines) | stat: -rw-r--r-- 2,018 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from __future__ import print_function
import tinyarray
import numpy
from time import time

################################################################
# Mock a numpy like "module" using Python tuples.

def tuple_array(seq):
    return tuple(seq)

def tuple_zeros(shape, dtype):
    return (dtype(0),) * shape

def tuple_dot(a, b):
    return a[0] * b[0] + a[1] * b[1]

class Empty:
    pass

tuples = Empty()
tuples.__name__ = 'tuples'
tuples.array = tuple_array
tuples.zeros = tuple_zeros
tuples.dot = tuple_dot

################################################################

def zeros(module, dtype, n=100000):
    zeros = module.zeros
    return list(zeros(2, dtype) for i in range(n))

def make_from_list(module, dtype, n=100000):
    array = module.array
    l = [dtype(e) for e in range(3)]
    return list(array(l) for i in range(n))

def dot(module, dtype, n=1000000):
    dot = module.dot
    a = module.zeros(2, dtype)
    b = module.zeros(2, dtype)
    for i in range(n):
        c = dot(a, b)

def dot_tuple(module, dtype, n=100000):
    dot = module.dot
    a = module.zeros(2, dtype)
    b = (dtype(0),) * 2
    for i in range(n):
        c = dot(a, b)

def compare(function, modules):
    print('{}:'.format(function.__name__))
    for module in modules:
        # Execute the function once to make the following timings more
        # accurate.
        function(module, int)
        print("  {:15} ".format(module.__name__), end='')
        for dtype in (int, float, complex):
            t = time()
            try:
                function(module, dtype)
            except:
                print(" failed   ", end='')
            else:
                print(' {:.4f} s '.format(time() - t), end='')
        print()

def main():
    print('                   int       float     complex')
    modules = [tuples, tinyarray, numpy]
    compare(zeros, modules)
    compare(make_from_list, modules)
    compare(dot, modules)
    compare(dot_tuple, modules)

if __name__ == '__main__':
    main()