Programmatically obtaining Big-O efficiency of code

后端 未结 18 1291

I wonder whether there is any automatic way of determining (at least roughly) the Big-O time complexity of a given function?

If I graphed an O(n) function vs. an O(n

18条回答
  •  死守一世寂寞
    2020-11-27 16:32

    It's easy to get an indication (e.g. "is the function linear? sub-linear? polynomial? exponential")

    It's hard to find the exact complexity.

    For example, here's a Python solution: you supply the function, and a function that creates parameters of size N for it. You get back a list of (n,time) values to plot, or to perform regression analysis. It times it once for speed, to get a really good indication it would have to time it many times to minimize interference from environmental factors (e.g. with the timeit module).

    import time
    def measure_run_time(func, args):
      start = time.time()
      func(*args)
      return time.time() - start
    
    def plot_times(func, generate_args, plot_sequence):
      return [
        (n, measure_run_time(func, generate_args(n+1)))
        for n in plot_sequence
      ]
    

    And to use it to time bubble sort:

    def bubble_sort(l):
      for i in xrange(len(l)-1):
        for j in xrange(len(l)-1-i):
          if l[i+1] < l[i]:
            l[i],l[i+1] = l[i+1],l[i]
    
    import random
    def gen_args_for_sort(list_length):
      result = range(list_length) # list of 0..N-1
      random.shuffle(result) # randomize order
      # should return a tuple of arguments
      return (result,)
    
    # timing for N = 1000, 2000, ..., 5000
    times = plot_times(bubble_sort, gen_args_for_sort, xrange(1000,6000,1000))
    
    import pprint
    pprint.pprint(times)
    

    This printed on my machine:

    [(1000, 0.078000068664550781),
     (2000, 0.34400010108947754),
     (3000, 0.7649998664855957),
     (4000, 1.3440001010894775),
     (5000, 2.1410000324249268)]
    

提交回复
热议问题