I wrote a very simple instant messenger client but, unfortunately, since I am still a relatively new programmer I am not familiar with what causes a program to eat up so much CPU time. Currently at runtime my program takes up 11mb in memory and 90-100% cpu usage!!
Without posting all the code, what factors contribute to cpu usage? I am not really sure what information would help others troubleshoot my program, so please let me know which specific details would be useful to you and I will provide them.
Thank you very much for any help.
12 6086
I wrote a very simple instant messenger client but, unfortunately, since I am still a relatively new programmer I am not familiar with what causes a program to eat up so much CPU time. Currently at runtime my program takes up 11mb in memory and 90-100% cpu usage!!
Without posting all the code, what factors contribute to cpu usage? I am not really sure what information would help others troubleshoot my program, so please let me know which specific details would be useful to you and I will provide them.
Thank you very much for any help.
I experienced high CPU usage in very long for loops or never ending loops.
Because your program takes up so much memory, are you creating many objects? Like MANY objects? Many BIG objects? Let me give you an example. I had 1 project run out of memory (Java has a cap on how much memory is used). We had to store a graph of 100,000 nodes. Yes, 100,000 huge objects.
I also created a Sudoku solver that used large objects too - 89 of them. This program didn't take much memory.
Does anyone know if a stack will cause a memory increase?
There are several objects... mainly objects used to deal with network connectivity and IO.
However the program is basically one recurring loop (until the user quits the chat client). This is unavoidable since it must be constantly looping and dealing with asynchronous network input as well as user keyboard input...
I am guessing then it is this loop that causes the high CPU usage? Are there any strategies for minimizing CPU usage?
There are several objects... mainly objects used to deal with network connectivity and IO.
However the program is basically one recurring loop (until the user quits the chat client). This is unavoidable since it must be constantly looping and dealing with asynchronous network input as well as user keyboard input...
I am guessing then it is this loop that causes the high CPU usage? Are there any strategies for minimizing CPU usage?
Are you actively waiting/checking whether or not some data is coming in from
the client(s)? If so, my bet would be on that for the high cpu utilization.
Better use separate threads per open socket and let them block in a read
method request. If the read blocks (because of no input) the thread will
relinguish the cpu and other threads will have a chance. Most of the time
none of them will be active.
kind regards,
Jos
If the read blocks (because of no input) the thread will
relinguish the cpu and other threads will have a chance.
Though that will definately need to be done for multiple clients, you can also block without threading.
I'm assuming you are using BufferReader. - while ((userInput = stdIn.readLine()) != null) {
-
// do stuff
-
}
This while loop will block also.
Though that will definately need to be done for multiple clients, you can also block without threading.
This while loop will block also.
Sure, if a thread has compadres it doesn't suddenly start to behave differently;
reads will block if there's no incoming data available. The op should made his/her
threads block (read: relinguish control) when no data is available), whether there's
one thread or more of them.
kind regards,
Jos
The op should made his/her threads block (read: relinguish control) when no data is available), whether there's one thread or more of them.
Actually, I made this same mistake before. - while ( userInput == null ){
-
userInput = stdln.readLine();
-
}
If I remember correctly (this was 2 years ago) the above code will never block; you must use the while condition I posted above.
Are you actively waiting/checking whether or not some data is coming in from
the client(s)? If so, my bet would be on that for the high cpu utilization.
Better use separate threads per open socket and let them block in a read
method request. If the read blocks (because of no input) the thread will
relinguish the cpu and other threads will have a chance. Most of the time
none of them will be active.
kind regards,
Jos
Thanks for the replies guys... that is exactly what I am doing. Unfortunately the solutions above, while making some sense are a little confusing to me (quite the programming nub unfortunately).
The client is very simple ( and the server likewise) there is only one socket connection (ie one host:port )
right now I have methods checking for network input and/or keyboard input in the same while loop... in fact the method handling keyboard and/or net io is so simple I may as well post it: - try {
-
-
while (!exit) {
-
if (scanKB.hasNextLine()) {
-
kbInput = scanKB.nextLine();
-
if (kbInput.equals("/quit")) {
-
switch (imc.disconnect()) {
-
case NO_ERRORS:
-
System.out.println("\nSuccessfully logged off");
-
break;
-
case IO_ERROR:
-
System.out.println("\nError while logging off");
-
break;
-
}
-
exit = true;
-
} else {
-
imc.sendMsg(kbInput);
-
}
-
}
-
if (imc.scanNet.hasNextMessage()) {
-
System.out.println(imc.printMsg(imc.scanNet.nextMessage()));
-
}
-
}
-
-
} catch (NextDoesNotExistException e) {
-
System.out.println("Error");
-
} catch (NullPointerException e) {}
So even with your examples above, I really am not sure what I could do with the above code to decrease CPU usage time...
EDIT: Ok, for some reason I cannot fix line 21 in my code above... for some reason it is posting a space in the nextMessage() method... no matter what I do I can't get it to post that line correctly... so please just realize that there shouldn't be a space there...
Also out of curiousity, how are you getting your code to post as java code with syntax coloring? I tried [JAVA][/JAVA] in place of [code] but that didn't work
Thanks!
Also out of curiousity, how are you getting your code to post as java code with syntax coloring? I tried [JAVA][/JAVA] in place of [code] but that didn't work
Thanks!
I guess, I'm not the right one to answer the question about multithreading, as it's something I've just started learning myself, but I can help you with your forum-related question: Just use [code=java] instead of [code] (but close it with the normal closing tag). That will also work with xml, html and many others... check the Code tag list to find all of them.
Greetings,
Nepomuk
So even with your examples above, I really am not sure what I could do with the above code to decrease CPU usage time...
Basically, what that while loop does is this: -
while (<some condition>) {
-
if (<input from keyboard>)
-
processKeyboardInput();
-
if (<input from socket>)
-
processSocketInput();
-
}
-
Suppose no keyboard input nor socket input are available, i.e. nothing happens.
Can you see that loop running around in, well, loops, doing totally nothing?
That's where your CPU load comes from.
If you had two threads instead, one watching (and blocking for) the keyboard and
the other doing the same with the socket both threads would simply block if
no input were available and CPU usage would be down to almost zero.
kind regards,
Jos
Thanks for the replies guys... that is exactly what I am doing. Unfortunately the solutions above, while making some sense are a little confusing to me (quite the programming nub unfortunately).
The client is very simple ( and the server likewise) there is only one socket connection (ie one host:port )
right now I have methods checking for network input and/or keyboard input in the same while loop... in fact the method handling keyboard and/or net io is so simple I may as well post it: - try {
-
-
while (!exit) {
-
if (scanKB.hasNextLine()) {
-
kbInput = scanKB.nextLine();
-
if (kbInput.equals("/quit")) {
-
switch (imc.disconnect()) {
-
case NO_ERRORS:
-
System.out.println("\nSuccessfully logged off");
-
break;
-
case IO_ERROR:
-
System.out.println("\nError while logging off");
-
break;
-
}
-
exit = true;
-
} else {
-
imc.sendMsg(kbInput);
-
}
-
}
-
if (imc.scanNet.hasNextMessage()) {
-
System.out.println(imc.printMsg(imc.scanNet.nextMessage()));
-
}
-
}
-
-
} catch (NextDoesNotExistException e) {
-
System.out.println("Error");
-
} catch (NullPointerException e) {}
So even with your examples above, I really am not sure what I could do with the above code to decrease CPU usage time...
Thanks!
The quickest way to fix your program: Place the nextLine() in the while loop condition. - while ( ( (kbInput = scanKB.nextLine()) != null ) ||
-
( (imcInput = imc.scanNet.nextMessage()) != null) ){
-
if (kbInput.equals("/quit")) {
-
.... //finish code.
I would suggest reading this tutorial Sockets but focus on the last section - Supporting Multiple Clients. This is a great example of threads.
Actually, I made this same mistake before. - while ( userInput == null ){
-
userInput = stdln.readLine();
-
}
If I remember correctly (this was 2 years ago) the above code will never block; you must use the while condition I posted above.
That most certainly isn't true; a readLine() method invocation will block when there
is no new line available. Your loop is exactly the same (functionally) as the loop
you don't like.
kind regards,
Jos
That most certainly isn't true; a readLine() method invocation will block when there
is no new line available. Your loop is exactly the same (functionally) as the loop
you don't like.
kind regards,
Jos
Thanks for fixing my confusion.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: BlackHawke |
last post by:
Our program, game program Andromeda Online (www.andromedaonline.net) uses
two programs- one to play the game, another to patch the game as updates
come out. Players actually launch the updater...
|
by: Warrick Wilson |
last post by:
I've got a web page that uses frames. One of the frames loads an HTML page
that redirects to a 3rd HTML page. This third page loads a Java applet -
ProScroll.class - that runs a "news ticker"...
|
by: Gaurav |
last post by:
http://www.sys-con.com/story/print.cfm?storyid=45250
Any comments?
Thanks
Gaurav
|
by: Cris |
last post by:
My question in a nutshell: Can a C header file be converted into a C#
interface? Details for why I want this below...
I am trying to use C# in lieu of C/C++ to build some libraries that
java...
|
by: Anoop |
last post by:
Hi,
I am new to this newsgroup and need help in the following questions.
1. I am workin' on a GUI application. Does C# provides Layout Managers the
way Java does to design GUI? I know that it...
|
by: Mythmon |
last post by:
I am trying to make a program that will basically simulate a chess
clock in python. To do this I have two threads running, one that
updates the currently running clock, and one that watches for a...
|
by: =?Utf-8?B?VkIgSm9ubmll?= |
last post by:
ASP.NET 2.0 / Visual Studio 2005 / VB.Net 2.0
I have a web interface that needs to launch a java application.
What a long strange trip it has been...
I am using Process.Start process start...
|
by: MimiMi |
last post by:
I'm trying to decrypt a byte array in java that was encrypted in C#. I don't get any error messages, just a result that's completely not what I was hoping for.
I think I am using the same type of...
|
by: MimiMi |
last post by:
I'm trying to decrypt a byte array in java that was encrypted in C#. I don't get any error messages, just a result that's completely not what I was hoping for.
I think I am using the same type of...
|
by: King Raz |
last post by:
The shootout site has benchmarks comparing different languages. It
includes C# Mono vs Java but not C# .NET vs Java. So I went through
all the benchmark on the site ...
...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
| |