Programmatically obtaining Big-O efficiency of code

后端 未结 18 1151

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:33

    I am curious as to why it is that you want to be able to do this. In my experience when someone says: "I want to ascertain the runtime complexity of this algorithm" they are not asking what they think they are asking. What you are most likely asking is what is the realistic performance of such an algorithm for likely data. Calculating the Big-O of a function is of reasonable utility, but there are so many aspects that can change the "real runtime performance" of an algorithm in real use that nothing beats instrumentation and testing.

    For example, the following algorithms have the same exact Big-O (wacky pseudocode):

    example a:

    huge_two_dimensional_array foo
    for i = 0, i < foo[i].length, i++
      for j = 0; j < foo[j].length, j++
        do_something_with foo[i][j]
    

    example b:

    huge_two_dimensional_array foo
    for j = 0, j < foo[j].length, j++
      for i = 0; i < foo[i].length, i++
        do_something_with foo[i][j]
    

    Again, exactly the same big-O... but one of them uses row ordinality and one of them uses column ordinality. It turns out that due to locality of reference and cache coherency you might have two completely different actual runtimes, especially depending on the actual size of the array foo. This doesn't even begin to touch the actual performance characteristics of how the algorithm behaves if it's part of a piece of software that has some concurrency built in.

    Not to be a negative nelly but big-O is a tool with a narrow scope. It is of great use if you are deep inside algorithmic analysis or if you are trying to prove something about an algorithm, but if you are doing commercial software development the proof is in the pudding, and you are going to want to have actual performance numbers to make intelligent decisions.

    Cheers!

提交回复
热议问题