简体   繁体   中英

A tool for calculating the big-O time complexity of Java code?

I have a question regarding time complexity (big O notation) for Java software. Is there a way to quickly calculate or test it (or any website that could calculate it for me would be welcomed). For example I would like to check it for the following snippet of code and possibly improve as well:

int dcount = 24423567;
int a = 0;
if (dcount == 0){
    a = 1;
}

String ds = Integer.toString(dcount);
String[] sa = ds.split("(?<=.)");
HashSet hs = new HashSet();
Collections.addAll(hs, sa);
a = hs.size();
if (dcount < 0)
    a--;

System.out.println(a);

As @emory pointed out, it is provably impossible to determine the big-O time complexity of an arbitrary piece of code automatically (the proof is a reduction from the Halting Problem ). However, there are tools that can attempt to measure the complexity of a piece of code empirically by running it on several different inputs. One such tool is described in the paper “Measuring Empirical Computational Complexity” by Goldsmith, Aiken, and Wilkerson. It works by attempting to do a regression on the program's runtime versus its input size. The tool, called trend-prof (discontinued), is available for reference.

Hope this helps!

I might be solving someone's homework, but the question was begging for a sane solution...

Counting distinct digits in a number requires no strings, sets or regular expressions, just some simple arithmetics.

The following method runs in O(n) time (n = number of digits in the input) and constant space:

int distinctDigits(int num) {
  if (num == 0) {
    return 1;
  }

  boolean[] digits = new boolean[10];

  while (num > 0) {
    digits[num % 10] = true;
    num /= 10;
  }

  int count = 0;
  for (boolean digit : digits) {
    if (digit) {
      count++;
    }
  }

  return count;
}

Making this work for negative numbers is left as an exericse to the reader ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM