pberkes / big_O

Python module to estimate big-O time complexity from execution time
BSD 3-Clause "New" or "Revised" License
324 stars 50 forks source link

Passing function arguments to measure complexity #57

Closed Zelatrix closed 1 year ago

Zelatrix commented 1 year ago

I have this implementation of the two-sum problem, and I want to test the time complexity. If I try and use this like in the documentation, it will tell me there is no argument target, could you tell me how I might use this library to test functions such as these?

def two_sum(arr, target):
     for i in arr:
             for j in arr:
                     if (i + j == target) and (i != j) and (i < j):
                             print((i, j))
pberkes commented 1 year ago

You should create a wrapper function that calls two_sum and keeps target fixed, e.g. lambda arr: two_sum(arr, 13).

Example code:

import big_o

def two_sum(arr, target):
    valid = []
    for i in arr:
        for j in arr:
            if (i + j == target) and (i != j) and (i < j):
                valid.append((i, j))
    return valid

target = 13
best, others = big_o.big_o(lambda arr: two_sum(arr, target), big_o.datagen.range_n, min_n=10, max_n=10000)

print(big_o.reports.big_o_report(best, others))

which gives

Best : Quadratic: time = 0.0081 + 1.5E-08*n^2 (sec)                 
Constant: time = 0.53 (sec)                                     (res: 2.4)
Linear: time = -0.21 + 0.00015*n (sec)                          (res: 0.19)
Quadratic: time = 0.0081 + 1.5E-08*n^2 (sec)                    (res: 0.0037)
Cubic: time = 0.12 + 1.5E-12*n^3 (sec)                          (res: 0.059)
Polynomial: time = 1.4E-07 * x^1.7 (sec)                        (res: 0.027)
Logarithmic: time = -0.66 + 0.15*log(n) (sec)                   (res: 1.5)
Linearithmic: time = -0.17 + 1.6E-05*n*log(n) (sec)             (res: 0.14)
Exponential: time = 0.0021 * 1^n (sec)                          (res: 34)
pberkes commented 1 year ago

BTW there is a linear solution for the problem you're trying to solve

pberkes commented 1 year ago

Closing as solved