0

I've written a function append() in Java and I need to analize its runtime complexity by O(N) and Θ(N).

This is the original question:

Suppose append()'s runtime complexity is t = O(N), it's mean that t can also be represented by t = C*N. (as C is a constant)

Therefore (t / N) = C.

If, for example, t = O(N^2), then (t / N^2) = C and so on.

use this method to find append() run time coplexity.

So I ran append() N times for 3 different Ns: 1,000, 5,000, 10,000.

long start = System.currentTimeMillis();
for(i = 0; i < N; ++i) {
    append();
}
long end = long start = System.currentTimeMillis();

System.out.println(end - start);

and I wrote down end-start which is the runtime in milliseconds.

Now, how can I use this info in order to get the time coplexity of append()?

Thanks in advance!

Community
  • 1
  • 1
Billie
  • 8,938
  • 12
  • 37
  • 67
  • 1
    You already have the time complexity, that's the O(N) thing. You're asking for the constant, and this is a murky use of asymptotic computational complexity **at best** -- why are you doing this? If you want to compare real-world performance, you can skip that part and compare the measured times directly. That's called benchmarking. –  Nov 01 '13 at 10:44

2 Answers2

1

You misunderstood the method. N is supposed to be the length of the string, not the number of function calls It should be

String str(n); // Or whatever how you create a string with n elements

long start = System.currentTimeMillis();
append();
long end = long start = System.currentTimeMillis();

System.out.println(end - start);

Then you run it for several Ns, and trying to find out which time coplexity it is. Try to divide t / N, then t / N^2, untill you find a constant answer.

LeeNeverGup
  • 1,096
  • 8
  • 23
0

With just one data point, you can't determine the time complexity of a function. A good way to empirically determine time complexity is to time the operation on inputs of multiple different sizes and look at the relative growth rate of the operation's runtime. For example, if the runtime roughly doubles as the input size doubles, the time complexity is O(n). If the runtime roughly quadruples as the input size doubles, the time complexity is O(n2).

Tje reason you need several data points is similar to why you need several points to determine a line. Given just one point, you can't tell what the slope or intercept is. When measuring time complxity, you can't sift out the relative contributions of the contsant term and the growth term.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065