Big O Time
Here's a great way to approximate the Big O time of your algorithm: just run it with differently sized inputs.
That's right, that's all you have to do* (*there's more to it, we'll get to it in a sec). You don't need to follow your inputs around, count any loops, look for best case and worse case scenarios. You can get a pretty good approximation by following the steps below.
1. Speed test your algorithm. Make sure you have at least 3 inputs - if you're working with an array, make sure there's 3 elements, if you have a string make sure there's at least 3 letters, etc. Larger inputs will make this test more accurate. Note down how fast your algorithm was.
2. Double the number of inputs.
3. Speed test your algorithm again. Got a number? Good.
4. Now, divide the second speed test result by the first one.
Once you've got that ratio, you're good to go! Simply compare your ratio to the following chart:
That's it! This doesn't cover all cases, but it does cover a huge amount of them.
Here's some code to test it out:
And here's my results:
Why does this work? It's related to what Big O actually means in practical terms. Doubling our inputs means doubling our n, whatever that n is. So, if we are operating in O(n^2) time, that means that if we double our input, we substitute 2n for n, which raises our execution time from n^2 to (2n)^2, which is 4n^2, which is 4 times larger than n^2 - you may note that (4n^2)/(n^2) = 4, which is the same division we did in step 4. Likewise, if we're operating in O(n^3) time, that means that doubling our input raises our execution time from n^3 to (2n)^3, which is 8n^3, which you can see is 8 times bigger.
So, what do we do about more exotic scenarios, like where our Big O time is, say, n log n? We can use the same principle of substitution to test a prediction about our Big O time. What is (2n log 2n)/(n log n)? Well...that depends on what n is. To do a proper test here, you'll need to actually substitute in how many inputs you have. If we have 5 inputs like in our code example and then we doubled to 10, the above expression calculates to 2.86. So somewhere around a little less than 3 would be a good ratio to look for.
Likewise, if we were looking for exponential time, we would calculate 10! and divide by 5!, which gives us...30,240. Doubling our inputs would increase our time to run by over 30,000 times. Exponential time is really, really slow!
Comments
Post a Comment