简体   繁体   中英

Why does my Java drawing code take so much CPU?

I learned Java for 3 days and made a code to draw a diagonal line made from X. It's taking 28% of my i5 CPU and I don't know why.

public class Main { 
    public static void main(String[] args) { 

        for (int i=0; i<20000; i++) {
            for (int j=0; j<i; j++) {
                System.out.print("  ");
            }
            System.out.println("X");
        }
    }
}

Edit 1: By the way, the output is kinda different between the first minutes I ran it and 10 minutes later. Weird. The distance between X get longer. Screenshot in 10 minutes later

Edit 2: I made another code just to know the "progress" where i has reached, when i reaches 100, 200, etc. it'll print that. But the code failed to compile on Windows, it compiles fine on https://www.compilejava.net . What's the problem?

public class Main {
  public static void main(String[] args) { 

for (int i=0; i<20000; i++) {
    for (int j=0; j<i; j++)
    {
    System.out.print("  ");
    }
System.out.println("X");
if ((i % 100)==0) {
System.out.println("Your cute code made it to the 100th lapse!");
}
}
}
}

To demonstrate what is happening here, consider the following code:

public static void main(String[] args) {

    int iTotal = 0;
    int jTotal = 0;
    for (int i = 0; i < 20000; i++) {
        for (int j = 0; j < i; j++) {
            jTotal += 1;
        }
        iTotal += 1;
    }

    System.out.println("Total I: " + iTotal);
    System.out.println("Total J: " + jTotal);
    System.out.println("Total:   " + jTotal + iTotal);
}

Here I've removed the printing and just used counters to help you see exactly what is happening here

The output:

Total I: 20,000
Total J: 199,990,000
Total:   19,999,000,020,000

Well, it is quite obvious that it will take a lot! it will iterate a lot of times! every value of j will be the summation of 20000 (1+2+3+4+...+19999+20000).

So the complexity is higher than O(n) .

Taking that into account, the number of prints you are doing is REALLY high. 20000 times X and summation of 20000 a white space!

Your code attempts to print 20000 'X' characters, as was observed in comments, but much worse, it attempts to print a total of about 400000000 space characters. Computers are fast, but that will still take some effort.

You're executing about 200 million print calls, if my high-school math is correctly remembered. You're producing 20 thousand lines of screen output. It doesn't seem surprising that uses a reasonably significant amount of CPU and takes some time to complete.

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