2

I wrote a Java program to download a HTML page. But CPU usage is near to 100%, while network usage is lower than 3%. It seems like that CPU became my bottleneck. How do I cut my CPU usage?

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
William_He
  • 357
  • 3
  • 4
  • 11
  • 3
    You're going to have to post you're source code, otherwise we can't help you other than telling you to use a profiler... – Yuval Adam May 07 '09 at 09:24
  • [Here's a simple and effective method to find out what's taking time.](http://stackoverflow.com/questions/266373/one-could-use-a-profiler-but-why-not-just-halt-the-program/317160#317160) – Mike Dunlavey Jul 07 '09 at 21:08

7 Answers7

6

Use a profiler (I like VisualVM), identify the bottleneck and fix it!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dfa
  • 114,442
  • 31
  • 189
  • 228
5

If you have a continuous while loop, give your program some sleep time between iterations. Downloading the web pages alone should not cause that much resource utilization though, you may want to look into a profiler to find out whats bottlenecking you. Perhaps posting the code here would let us help you a bit more.

John T
  • 23,735
  • 11
  • 56
  • 82
3

One very simple thing you can do to identify the problem is just grab a few stack traces. ctrl-/ctrl-break/jstack/jconsole/visualvm. If the program is catastrophically spending a lot of its time where the performance problem is (reasonably likely), then you should easily see the problem.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
2

If your CPU usage is near to 100% for a long period of time, then most probably you have an error in your code (infinite loop or something). Try to profile your application to see what is happening. Start from printing the current time from various points at your code. If you still can't find that out, a profiler will be needed.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
  • If the loop is infinite, grabbing a couple stack traces will find it. If the loop is _not_ infinite, but merely long, the same method works. – Mike Dunlavey Jul 07 '09 at 21:14
1

Maybe you are polling for data too fast...

I would try to change the code to event-driven notification.

Regards.

ATorras
  • 4,073
  • 2
  • 32
  • 39
1

When you read, are you reading a char/byte at a time? That will load the OS quite a bit.

Use a BufferedReader, and/or try to read using either read(char[]...) or readLine() depending what you are reading into.

KarlP
  • 5,149
  • 2
  • 28
  • 41
0

Are you, by any chance, parsing the HTML using the built in Java XML DOM stuff? From past experience, it can result in some pretty hefty CPU usage (and it's the slowest implementation I've ever seen, honestly). If so, you might want to consider a third-party library for XML parsing (JDOM, for instance).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RHSeeger
  • 16,034
  • 7
  • 51
  • 41