• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 760
  • Last Modified:

100% CPU usage


I'm developing in Delphi 3 under Windows 2000.

I have written software to retrieve messages from a newsserver. Whenever I'm downloading a message the CPU-usage goes quickly to a 100 percent. When this happens my computer isn't very responsive anymore.

What's the best way to find the cause of this behaviour?

I have read a question here about that stating I had to be careful with the command 'Application.ProcessMessages' which I use throughout my software to let the rest of the system get CPU-time too.
  • 9
  • 6
  • 3
  • +5
2 Solutions
First you need to detect which part of the code is causing this behaviour. e.g. put ShowMessage statements after every line in the particular procedure, until you find out which line it is. If it is a procedure/function call, go to that procedure/function and repeat the process. If you don't have the source of the problematic part, maybe because it is from a third-party component, try another component. Things like that.

When using Application.ProcessMessages within Intense loops that aren't time critical you SHOULD always use Sleep(SomeSmallValue);

Application.ProcessMessages uses the same amount of CPU for every instruction that all other Procedures/Functions do...

I believe i read that even Sleep(0) would do the trick...i generally use Sleep(5) when i have intense loops..


You may want to put the work in another thread.
In the execute method you do an iteration of the work.
'Then (only there) you do a Sleep(sometime)
e.g in the thread...

  while (not Terminated) do // run indefinately
    //Synchronize(TransferToGui); // if required copy results etc. to main thread
    if not (ExceptObject is EAbort)
      then Synchronize(ThreadException);

Choose the sleep value determined by how much you want this thread to take over the machine. The form interacts smoothly with user.

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Oh yeah, get rid of Application.ProcessMessages.
Use v.sparingly (if at all).
detempelAuthor Commented:
I have isolated the event that is called 'intense' when a message is being downloaded. Inside that event I have put the following code:

MsgContents.Text := MsgContents.Text + DocOutput.Datastring

Using the method of placing 'showmessages' I have traced that this code takes up about 10% of processor time each time it's called. If the event fires 10 times fast then the processor is working 100%.

After moving the code to a place where it gets executed when the complete message is downloaded and putting the following code in the intense event:


Things are better. The processor doesn't reach 100% anymore that quickly and other processes are not slowed down that much anymore.

I have some questions contemplating your answers:
1) Can you explain in more detail why I shouldn't use 'Application.ProcessMessages';
2) Can you explain in more detail what a 'thread' is;
3) How do I 'make' a new thread, maybe you can give me a real life example;
4) Is the command 'sleep' based on freeing up the processor for other processes;
5) If I make a separate process (thread?) can't I lower the priority of such a process.

But I was thinking isn't is possible to do the following:
- put the intense code in a separate process A;
- restrict the process A to use a maximum of say 10% of the capacity of the processor;
- lower the priority of the process in respect to other processes.

This way I will be sure other processes get processor capacity too and won't be slowed down which is unacceptabe.
1) Application.ProcessMessages has Delphi check the message queue and handle any pending messages. This does make sure that the GUI of your application does not "hang" when the main thread (!!!) executed some lengthy operation. Application.ProcessMessages does NOT free up CPU resources, Sleep(0) does (by telling the thread sheduler of windows that this thread does not need all the time available. Also, Application.HandleMessage does signal an "idle" state of the CPU.

2) A thread is a parallel execution of code, sort of a second task in the same application. This means that, for instance, two procedures are executed at the same time. Therefore a thread is ideal for background processing, it allows to have the main thread (which should be handling the GUI etc.) free of any slow processing code. The processing code is then executed in parallel without interfering with the main thread, therefore eliminating the need to care about Application.ProcessMessages etc. because the application is not locked up.

3) Derive a new class from TThread, and overwrite the Execute method:

          constructor Create;
          procedure Execute; override;
constructor TMyThread.Create;
     inherited Create(False); // create thread unsuspended
     FreeOnTerminate:=True; // we don't want to care about freeing it manually

procedure TMyThread.Execute;
     while not Terminated do begin
          // do whatever you want to do in the background here.
          // it will not interfere with the GUI, since it is running in its own thread

Then, in your code:

     MyThread: TMyThread;
     MyThread.Terminate; // tell the thread to stop working.
     // will set Terminated to true, so that the loop in Execute will stop.

4) The Windows thread/task sheduler assigns timeslices to each process and thread. If the processing in a thread is not very time critical and the thread does not need all its timeslices, it should notify the sheduler of this fact. This is done with Sleep(). Whenever called, the sheduler terminated the currently running time slice and continues execution on the next thread. Therefore, a Sleep(0) does a perfect job of signaling that the current timeslice is not needed for processing. Dont worry, timeslices are short, and your thread will be handled again very soon.

5) Of course you can. The thread has a property for the priority. Hote, however, that the thread priority is just in comparison with the other thread in the same process. The process priority determines how often a process will receive time, and the thread priority determines how the time is to be distributed among the thread of that process. If you use Sleep() to release timeslices at the right places, you usually don't need to play around with priorities at all.

About your theory:
- having a thread is pretty much having another process, but wqhich runs in the same context (e.g. variables etc. can be accessed).
- restricting to a maximum is not good. Why not allow the thread to have as much CPU time as there is available? Putting in Sleep()s will greatly enhance the response of windows even if your code does use 100% CPU.
- can be done, but is usually not necessary.

About your application:
     MsgContents.Text := MsgContents.Text + DocOutput.Datastring;
This is an expensive operation, because each time the string gets longer, a new memory block has to be allocated, the contents of the string has to be copied there, and the old block has to be released. It gets slower the longer your message is. Instead, use a TMemoryStream which is much better suited for "accumulating" data in memory.
1 : There is no reason why you shouldn't call Application.ProcessMessages as long as you aren't in a separate thread, Application.ProcessMessages does just what the procedure says, it processes messages sent to the application, so that Taskmgr doesn't think it is a hung application...

2 : using a thread is a way to let the application do several things at once...

3 : There are examples of threading in the demos directory of delphi

4 : actully yes, it makes your application Sleep for a period of time so it doesn't use any cpu...

5 : there are priority settings in threads, but without actually (seeing your code, or getting more information about your application, how it works, a flow chart would be nice =)) it's impossible to say if threading your application will give you any advantages.

That was a great comment AvonWyss, the best i've seen in a while...

I just love it...=))

Thank you very much, raidos. Doing my best... :-)
detempelAuthor Commented:
Wow, great answer AvonWyss.

I'll try it out when I get home.
You're welcome. Regarding my comment about using a TMemoryStream, it may also be of interest to you to know how to transfer data from the stream to a string or a stringlist. Both is pretty easy:

* To one string:

* To a TStrings (for instance, a TStringList):
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if they are still open in 14 days.  Experts, please post closing recommendations before that time.

Below are your open questions as of today.  Questions which have been inactive for 21 days or longer are considered to be abandoned and for those, your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.

*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations.
If you are interested in the cleanup effort, please click this link
POINTS FOR EXPERTS awaiting comments are listed in the link below
Moderators will finalize this question if in @14 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
Thanks everyone.
Moderator @ Experts Exchange
As you can see, even two other experts did congratulate my comment, so I believe that it should be fully answering the question.
Except it repeated what I had already stated with a lot of extra baggage.
Also only I present the proper way of using sleep and also to avoid 100% cpu...
AvonWyss answer simply does not adress 100% cpu usage.

If it's the expert answer you want....
Plus, Ladies and Gentlemen, I give you Dark King, who is one very happy customer of Ex-Ex with this PAQ of mine with the very same promblem and answer.

detempelAuthor Commented:
I'm still working on this. Right after I got the answer regarding using a thread my computer shut down automatically after starting up Windows 2000.

Since that I have been busy setting up a clean system involving installing a lot of software again. I still want to try out to get a thread to work.

The only reason I still haven't accepted an answer is that I want to try out making a thread (and maybe asking extra questions about a thread) before accepting an answer.


Erik Tempel.
SteveWaite, if you pretend that I don't address the 100% CPU usage and only repeat your answer with a "lot of extra baggage", I don't believe that you have even read all of my comment. It's true that I also suggest using Sleep(), but even then, I suggest using it exclusively with a value of 0 and explain why and when to use it, while you suggest to choose a higher value. So it should be obvious that this is not a plain repetition.

Erik, glad to hear from you. We look forward in assisting you with the thread question.
Except that my answer was first which obviously jogged your memory AvonWyss!

Perhaps you should have waited for me to explain my answer in more detail rather than do it for me. Which is the proper way at Ex-Ex.
Thank you.
So, SteveWaite, are you saying that the "proper way at Ex-Ex" is to post a shortened answer and - sometime later on - post a more complete version of it? Well, in my case, I usually try to provide complete answers from the very beginning. Anyways, there is no reason to debate further on this, since Erik will evaluate all our answers and award point to the expert(s) which he feels helped him most.
No, AvonWyss (hands on hips), since I do not assume they know nothing at all but allow them to ask further, that is all, so wind yer neck in.
As far as I am concerned, I would prefer 'dead' questions simply deleted.

I see AvonWyss and a few others too often trying to up thier points tally simply by goading the admin to hand them the points.

detempel -->  You logged in here today, please do update and decide about your questions here in terms of evaluating the responses.  If you need my help to split points, I'm happy to help you if that is the case.
Thanks to all,
Moondancer - EE Moderator
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
Post your closing recommendations!  No comment means you don't care.
The Wisdom of Solomon Justice ... Let's split the baby :)))

No comment has been added lately (19 days), so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area for this question:

RECOMMENDATION: split points between SteveWaite http:#6900630 and AvonWyss http:#6902124

-- Please DO NOT accept this comment as an answer ! --


EE Cleanup Volunteer

Remember you (all) can object this recommendation if you disagree, just leave a post here explaining why are you objecting and what should be done instead.
Within 7 days probably this thread will be closed, so, hurry up! : )

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 9
  • 6
  • 3
  • +5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now