File size: 4,795 Bytes
4b876a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
__author__ = 'ferrard'

# ---------------------------------------------------------------
# Imports
# ---------------------------------------------------------------

import time
import matplotlib.pyplot as plt
import scipy as sp

# ---------------------------------------------------------------
# Interface - Timing function
# ---------------------------------------------------------------


def time_them(k, m, *functions):
    """Times the functions (accepting one argument - n) on k values of n up to m

    Stops the timing once the function's execution takes:
    - more then 2 sec
    - more then 1 sec longer then on previous value of n
    """
    n_values = list(range(1, m))
    if m > k:
        n_values = list(range(1, m, m//k))
    results = []
    for i in range(len(functions)):
        print("Testing function " + functions[i].__name__)
        results_for_f = []
        for n in n_values:
            print("\tInput size " + str(n))
            before = time.time()
            functions[i](n)
            after = time.time()
            results_for_f.append(after - before)
            if results_for_f[-1] > 2 or (len(results_for_f) > 1 and results_for_f[-1] - results_for_f[-2] > 1):
                break
        results.append(results_for_f)

    for i in range(len(functions)):
        plt.plot(n_values[:len(results[i])], results[i], label=functions[i].__name__)
    plt.legend()
    plt.show()

# ---------------------------------------------------------------
# Interface - try out
# ---------------------------------------------------------------


def n_sqrt_n(n):
    res = 0
    for i in range(n*int(sp.sqrt(n))):
        res += 1
    return res


def n_squared(n):
    res = 0
    for i in range(n*n):
        res += 1
    return res

# ---------------------------------------------------------------
# Interface - Sum to
# ---------------------------------------------------------------


def sum_builtin(n):
    """Sums numbers up to n using built-in function - O(n)"""
    print(sum(range(n)))


def sum_explicit(n):
    """Sums numbers up to n explicitely - O(n)"""
    total = 0
    for i in range(n):
        total += i
    print(total)


def sum_analytic(n):
    """Sums numbers up to n, analytically -  O(1)"""
    print(n*(n + 1)//2)

# ---------------------------------------------------------------
# Fibonnachi numbers
# ---------------------------------------------------------------


def fib_n_naive(n):
    """Naive (recursive) way to compute Fibonacci's numbers. O(F(n))"""
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fib_n_naive(n - 1) + fib_n_naive(n - 2)


def fib_n_efficient(n):
    """Efficient way to compute Fibonacci's numbers. Complexity = O(n)"""
    a = 0
    b = 1
    for i in range(n - 1):
        c = a + b
        a = b
        b = c
    print(b)
    return b


def fib_n_closed(n):
    """Closed-form computation Fibonacci's numbers. Complexity = O(n)

    WRONG! Problems with precision!
    """
    fi = (1 + sp.sqrt(5))/2
    res = int(round((fi**n - (-fi)**(-n))/sp.sqrt(5)))
    print(res)
    return res

# ---------------------------------------------------------------
# Sorting
# ---------------------------------------------------------------

BOUND = 1000
# BOUND = 1000000  # try this bound - the linear sort will much more slow down


def sort_selection(n):
    """Sort n random numbers - using inefficient quadratic sort - O(n^2)"""
    l = list(sp.random.random_integers(0, BOUND, n))
    for i in range(n):
        for j in range(i + 1, n):
            if l[i] > l[j]:
                tmp = l[i]
                l[i] = l[j]
                l[j] = tmp


def sort_inbuilt(n):
    """Sorts n random numbers - using efficient inbuilt function - O(n log n)"""
    l = list(sp.random.random_integers(0, BOUND, n))
    l.sort()


def sort_linear(n):
    """Sorts n random numbers bounded in a small range - using efficient linear sort, called Counting sort - O(n)"""
    l = list(sp.random.random_integers(0, BOUND, n))
    counts = [0]*(BOUND + 1)
    for i in l:
        counts[i] += 1
    counter = 0
    for i in range(len(counts)):
        for j in range(counts[i]):
            l[counter] = i
            counter += 1

# ---------------------------------------------------------------
# Main
# ---------------------------------------------------------------


def main():
    # time_them(20, 1000, n_sqrt_n, n_squared)
    # time_them(20, 1000000, sum_builtin, sum_explicit, sum_analytic)
    # time_them(20, 100, fib_n_naive, fib_n_closed, fib_n_efficient)
    # time_them(20, 1000, fib_n_closed, fib_n_efficient)
    # time_them(20, 10000, sort_inbuilt, sort_linear, sort_selection)
    time_them(20, 1000000, sort_inbuilt, sort_linear)

if __name__ == '__main__':
    main()