How do I start optimising my Java code? - CPU is at 100%

六眼飞鱼酱① 提交于 2019-12-01 11:41:44

The problem doesn't seem to be in the methods which are being used a lot, it's how frequently you call them which appears to be why they are showing up so frequently. I'd check for all of the calls, see if any are superfluous then go to the third most time consuming method. After that, I would check my algorithms for being particularly intensive. Also, check all method calls and make sure they're not being run without need.

I know this isn't solving the problem itself, but its a start with the information given.

EDIT: The while loop is an infinite loop causing a for loop to run in which every item in an array has been checked to see if its been reset. You can replace this with an observer pattern where when an object is reset, it notifies the observing object which then performs that set of steps. This way you don't have an infinite loop and you cut down on the usage of .isReset(). This is in the main method of Class 1.

Edit 2: Here's the example of an implementation of the observer pattern which is on wikipedia.

"How do I start optimising my Java code?"

You start by profiling it first.

Start with the most intensively used method in your readout and move to less and less intense methods until you find one with a loop construct (for, while). Check the loop construct to see if it is doing too much work, and see if the functions that call this function call it often.

i.e (pseudocode)

dotProduct(vector a, vector b)
{
  //create vector dot product here
  maths maths maths
}

calc(data)
{
  for obj in data:
    dotproduct(obj, foo)
}

dotProduct will use the most CPU time, but calc is the place to start - can we cache results? are we recalculating data? Are we iterating through data in a stupid way?

Judging by the function names "isReset()" and "isRunning()" being called a lot, I would guess that you're wasting CPU time polling for a condition/event. Java should have some sort of semaphore/signalling system that you can use to let the do-er notify the wait-er exactly when the event occurs.

First things first. you have a warning in you code somewhere, as that you have used the annotation

@SuppressWarnings("serial")
. While this very well may have nothing to with your cpu maxing out. Fix this first and you very well may stumble on the problem.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!