Program/algorithm to find the time complexity of any given program

后端 未结 4 2034
北恋
北恋 2020-12-16 04:13

I like to know whether it is possible to \"write a program or algorithm\" to find the time complexity of any given program

4条回答
  •  感动是毒
    2020-12-16 04:37

    Proving the complexity of an arbitrary algorithm is not possible but in principle you could estimate it:

    1. choose n, the size of the input
    2. run the algorithm
    3. observe t(n), the time needed to run the algorithm for input of size n
    4. choose another n, repeat steps 2 and 3 until you have a lot of data
    5. regress t(n) on n, n^k, log(n), n log(n), n!, or any other term that might be appropriate
    6. choose a term with statistical significance and declare that to be your estimated complexity of the algorithm

    There are any number of pitfalls to this approach

    1. This will not prove anything, only estimate
    2. If t(n) gets really large for large n, it will take a long time to collect enough data for your analysis
    3. There are many ways that this approach can be fooled unless you use huge values of n. For example, this algorithm will look like O(1) unless you use astronomical values for n

      sleep for 10 days
      run an O(n log(n)) sorting algorithm
      

    And other SO users can come up with many more. But in some cases, like when you do a complexity analysis of an algorithm and want to verify it empirically, this is still a useful approach.

提交回复
热议问题