Short code snippet uses a lot of CPU. Suggestions on how to optimize?

What I want to do is to ping a specified address after a specified delay, and then extract the delay and store it in a comma-separated file (optimally along with a timestamp). I could not find any way to make the delay with the ping command in windows XP, so I created a Timer for the task. The program does the trick, but the CPU usage jumps to about 50% when running the application. I'm kind of new to Java, and don't know all the do's and don'ts of threads and infinite loops. Any suggestion to how to optimize the code would be appreciated.
package WitelcomMonitor;
import java.io.*;
import java.util.Timer;
import java.util.TimerTask;
public class WitelcomMonitor {
     Timer timer = new Timer(true);
     int counter;
     public WitelcomMonitor(long delay){
          timer.schedule(new TaskPerformer(), 0, 5000);
     class TaskPerformer extends TimerTask{
          public void run(){
               try {
                    String line;
                    String[] command = {"ping", "-n","3", "123.12.12.1"};
                    Process p = Runtime.getRuntime().exec(command);
                    boolean append = true;
                    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("delayprofile.txt",append)));
                    String subline;
                    int indexEnd,indexStart;
                    while ((line = input.readLine()) != null) {
                         if(line.contains("TTL")){
                              counter++;
                              indexStart = indexEnd = line.indexOf("ms");
                              do {
                                   indexStart--;     
                              } while (line.charAt(indexStart)!='=');
                              subline = line.substring(indexStart+1,indexEnd);
                              out.print(subline.concat(","));
                              System.out.println(subline.concat(","));               
                         //System.out.println(counter);
                    input.close();
                    out.close();
               catch (Exception err) {
                    err.printStackTrace();
     public static void main(String[] args){
          long delay = 5000; //milliseconds     
          new WitelcomMonitor(delay);
          while(true);
}

Ok, so the while(true) statement by itself drains the CPU, while by asking the main thread to sleep in ten seconds intervals just to sleep again for ten seconds etc. will keep the load on the computer low. Yeah, it worked so I'm happy. I'm not sure though how I can avoid a new thread, as I have to extend TimerTask which requires that I override the run() method. This in turn causes a thread to be run in addition to the main thread. How do you suggest that I avoid this?

Similar Messages

  • Scroll is using a lot of CPU

    Hello
    In my application I have a general scroll that contains a lot of tables and tabs.
    The scroll is working slow and is using a lot of CPU power.
    Table scrolls are working fine.
    Could be something wrong in the code?
    Thank you

    Of course there could be something wrong in your code. Can you post an SSCCE that reproduces this behaviour?

  • Seems Firefox is suddenly using a lot of CPU power

    My desktop, recently, started sounding like it was really laboring while I wander around the net. And there's a delay as I type messages like this... the letters show up a second or two behind the keystrokes.
    I looked at CPU usage (Win XP with all updates) and while I'm doing this, it sometimes peaks to 35% or higher for Firefox.exe.
    My laptop has recently started telling me Firefox is using a lot of memory and I should close and restart Firefox. (Also updated Win XP)
    It's becoming a big PITA...

    It didn't show up when i searched for the problem on Google and it didn't show up when i search here on Firefox's support site either.
    And the reason it didn't because it's mostly not about my problem.
    '''If' it was one of those things then i would have a high CPU usage the minute i opened my browser, but i don't.'''
    '''It will use a lot of CPU power (after a couple of hours) even if i don't do anything '''
    And yes hardware acceleration is on and so is submit performance data and i use Ad Block Plus, and there isn't a correctly working theme or add-on out there that could use 50-60% of a 3.2GHz quad core CPU
    I don't think this is something that can be fixed that easily

  • Is Photos using a lot of CPU?

    Photos is now using a lot of CPU. This is after it converted my iPhoto library. Is this normal? Is anyone else seeing this on their machine? Here's a screen shot with
    Photos hidden (not actively being used).

    It's probably still building the library and optimizing. Mine is still way up there as well. I'm going to let it run over night and see where it's at in the morning.

  • Ditto Using A Lot Of CPU?  Fans Run Often

    It seems to be the culprit in causing the fans to run fast since installing SL. I stop the process from the Activity Monitor but it starts back. AM shows ditto at 90% when it's running. The fans come on, I stop ditto and they slow down, later the fans come on again, I check and ditto is running again and at 90%...............

    Actually resolved this. Related to unzip issue.
    Attempting to unzip some files locks up the Archive Utility. Force Quitting the Archive Utility leaves ditto open and using a lot of CPU.
    Therefore, I'm using The Unarchiver (as kindly suggested by someone on my unzip problem post) at least until Apple updates the Archive Utility.

  • ITunes using a lot of CPU

    I had been using iTunes for a few hours on my Powerbook and noticed it was using a lot of cpu (about 30-40%) for just playing a song.
    I quit the application, and then noticed the following message in my console at around that time:
    Jan 19 17:23:16 My-Powerbook mDNSResponder: -1: DNSServiceResolve("My Music", "daap.tcp.", "local.") failed: Client id -1 invalid (-65549)
    This looks like it was doing some DNS operation that couldn't be completed?
    The application now is working fine after restarting it with the usual sub-10% activity level.
    This is iTunes 6.0.2 and the ministore is disabled. Playing was just to local speakers from the local library.
    Thanks for any help
    Ian

    ..Step by Step to fix your Mac
    They will just say it's a software problem you need to fix most likely.
    However if you have exhausted your software fixes and/or Hardware Test gives something, it could be a hardware problem, but likely it's software for what your mentioning.

  • Firefox 9 after a while starts using a lot of CPU power, need help!

    After a while (2 hours or more) firefox 9 (not the plugin container) starts eating up more and more CPU power, usually just to 25% (because usually i close it and restart it after that), but today i had work to do and i couldn't restart it right then and that resulted in firefix using about 50-60% of a 4 core 3.2GHz CPU (AMD Phenom II X4 955).
    I'm not doing anything extraordinary just writing emails and just plain normal browsing)
    I only notice this because my CPU fan speeds up and makes a lot more noise if using more then 20% CPU power.
    I'm pretty sure regular users wouldn't notice anything until it started to slow down their whole PC
    I'm using Firefox 9.0.1 running on Win 7 64bit, i have about 20-30 tabs always open (loading) and i haven't tried disabling any add-ons.
    I've read on forums that this might have something to do with flash data piling up, or with having to many tabs open.

    It didn't show up when i searched for the problem on Google and it didn't show up when i search here on Firefox's support site either.
    And the reason it didn't because it's mostly not about my problem.
    '''If' it was one of those things then i would have a high CPU usage the minute i opened my browser, but i don't.'''
    '''It will use a lot of CPU power (after a couple of hours) even if i don't do anything '''
    And yes hardware acceleration is on and so is submit performance data and i use Ad Block Plus, and there isn't a correctly working theme or add-on out there that could use 50-60% of a 3.2GHz quad core CPU
    I don't think this is something that can be fixed that easily

  • If i lock my Mac using iCloud "Find My.." with a code, but now i have forgotten the code i used but have my Mac bac.  How can i Unlock it????

    If i lock my Mac using iCloud "Find My.." with a code, but now i have forgotten the code i used but have my Mac bac.  How can i Unlock it????

    If you cannot remember the passcode, you will need to restore your device using the computer with which you last synced it. This allows you to reset your passcode and resync the data from the device (or restore from a backup).
    If you restore on a different computer that was never synced with the device, you will be able to unlock the device for use and remove the passcode, but your data will not be present.
    You may have to force iPad into Recovery Mode
    http://support.apple.com/kb/ht1808

  • Flash uses a lot of CPU

    Clean sl installation, latest flash. I just found out that flash uses quite a lot of CPU, it wasn’t this bad with Leopard. Sometimes when browsing on regular news sites, I see flash uses up to 130% of my CPU. That is a failure!
    I am not interested in any plugin, so I just temporary disable plugins from Safari preset meny.
    • Keyboard short cut: *Command + comma—key* ( might vary for english setup).

    William Kucharski wrote:
    People have been complaining about this for years to Adobe; amazingly enough it actually uses less CPU to view Flash content running in Windows under Parallels or VMWare.
    Sigh.... for years?
    I uninstalled the player form my system, and reinstalled it again. Now the performance on safari got better... but still eating 30-40% only moving a few movieclips...

  • Long running processes using a lot of CPU

    Hi all,
    We have a clustered environment and on both the DB nodes there are processes that is taking a lot of CPU and runs a really long time. The load of the servers get really high and performance degrades drastically.
    I've traced the processes and the module is usually a combination of the following:
    icx.por.rcv.server.ReceiveItemsAM
    icx.por.reqmgmt.server.ReqMgmtAM
    I know it has something to do with Purchase Orders.
    Can someone please give me more info on this processes and what I can do about them?
    Thanks in advance.

    ..Step by Step to fix your Mac
    They will just say it's a software problem you need to fix most likely.
    However if you have exhausted your software fixes and/or Hardware Test gives something, it could be a hardware problem, but likely it's software for what your mentioning.

  • Does Time Machine use a lot of CPU power if I leave it on ?

    If I leave Time Machine on and have it automatically back up every hour, will that use much of my cpu ?

    minimal usage after the initial backup.
    Look at your Activity Monitor and see for yourself.
    >Applications/Utilities/ActivityMonitor.app>CPU

  • Phone application is using a lot of CPU

    Hi everyone, I'm new here but I've been a blackberry user for several years with only a few minor issues.
    Model: Curve 9300, provider- orange
    This issue presented itself a week ago, seemingly unprompted by me. I didn't (intentionally) do a software update and I didn't download any new apps.
    For the past week now, my blackberry's battery life has only been lasting about 6 hours at a time, maximum. Previously, it would go a full day or more without dying on me. I assumed this was just some rapid deterioration of the battery but when I did some googling today, I found that this is a common issue that a few people had in the summer of 2011. I have also noticed the little black timer appearing on the screen a lot at random points.
    When I checked my CPU useage under the Application management section, it says my phone application has been in use for 16 hours of today, same for yesterday, however when I look back at the previous week, I see that I'd only used 20 hours in an entire week back when the phone's battery worked to a satisfactory level. I'm guessing this is what is draining my battery life and so buying a new battery won't resolve the issue. As I've been typing this, the phone useage has jumped up to 100% for no reason at all.
    A few sources say to update my software but it says I have the newest version. (6.0 bundle 2534). 
    Sorry if I'm a little useless about this, I've never even knowingly updated the software before so I may take a little guiding through everything.
    Thanks to anyone who can help me!

    Of course there could be something wrong in your code. Can you post an SSCCE that reproduces this behaviour?

  • New take on the old "Finder using a lot of CPU"

    Been searching a lot and found next to nothing but "reinstall OS X" advice around.
    My situation:
    I run a 1 CPU, 4 core 2008 Mac Pro with all updates.
    My Finder constantly uses 65 - 80 % CPU on one of the cores. It also has 16 - 18 threads open. It does not matter how many (or few) windows or applications I open. It will do this constantly.
    I have done a little nosing about but found very little. The weird thing is that if i rightclick on the desktop, the CPU will immediately drop to normal usage.
    What on earth is going on here?!?
    -KJ

    And out of the blue, my problem returns. Exactly the same symptoms as last time, save for the CPU usage now being 40 - 60 % of one core.
    Right clicking the desktop drops the usage down to normal levels in a split second.
    I tried killing the process now, and it seems to have worked, but there has to be a better way... Did not remember the advice about safe mode before I killed it, but my guess is that doing that will be like killing the process and probably would fix it for some time.
    When I sample the process, I find the statistics:
    Sort by top of stack, same collapsed (when >= 5):
    _semwaitsignal 7945
    semaphoretimedwait_signaltrap 4765
    machmsgtrap 3871
    kevent 1589
    select$DARWIN_EXTSN 1589
    0x51e4a 709
    0xe3670 78
    0xe3674 14
    0x51e4d 9
    0xe366d 9
    0xe3664 8
    getdirentriesattr 7
    0x51e46 6
    0x51e53 6
    0xe365e 6
    0x51e35 5
    0x51e48 5
    Sample analysis of process 370 written to file /dev/stdout
    There has to be a logical explanation for this.
    I have upgraded to 10.5.7 since the last time I saw this problem.
    -KJ

  • Getting messages "startup disk is full" and activity monitor is showing "syslog d" is using a lot of CPU.  I'm planning on getting more memory for my late 2008 model Macbook but wondering if there's something that is causing problems that I can also fix.

    I had closed out of all of my programs but heard the internal fans running so I checked the activity monitor.  It shows syslog d as the top process using the CPU right now.  I have no idea what that means.
    I read a thread about the startup disk being full and how you can free up memory.  I have an airport extreme so TimeCapsule is backing up everything.  I do have a bunch of pictures on iPhoto on the laptop;  could move those to another location but I'm a little gunshy.  I know they are on the TimeCapsule but I would like to save them to a second place before deleting from laptop just to be sure.  I went through several things yesterday and emptied trash, etc.  I wasn't able to locate the hidden files that the thread about the startup disk being full was referencing --- they were talking about large emails that were causing processes to happen taking up the CPU.... I wasn't able to find out if that was the case for me. 
    Also I'm going to look into getting another 2MB of memory and installing it on the Macbook, so I can upgrade to the latest OS.  Anyone have an idea if that is worth the $$$ over buying a new laptop?  Or anyone have ideas as to where to buy memory, etc.
    Any ideas - help!

    Go step by step and test.
    1. Start up in Safe Mode.
        http://support.apple.com/kb/PH11212
    2. Empty Trash.
       http://support.apple.com/kb/PH13806
    3. Disk space / Time Machine ?/ Local Snapshots
      Local backups
       http://support.apple.com/kb/ht4878
    4. Delete old iOS Devices Backup.
        iTunes > Preferences > Devices
        Highlight the old Backups , press “Delete Backup” and then “OK”.
        http://support.apple.com/kb/HT4946?viewlocale=en_US&locale=en_US
    5. Re-index Macintosh HD.
        This will take a while. Wait until it is finished.
        System Preferences > Spotlight > Privacy
        http://support.apple.com/kb/ht2409

  • Finder using a lot of CPU?

    Why would the Finder be using 80-100% of the CPU when I'm doing things in Safari? i'm considering taking my mac into apple to get diagnosed, but I'm wondering what would cause this to happen...

    ..Step by Step to fix your Mac
    They will just say it's a software problem you need to fix most likely.
    However if you have exhausted your software fixes and/or Hardware Test gives something, it could be a hardware problem, but likely it's software for what your mentioning.

Maybe you are looking for

  • Check material cost when post goods issue

    Hi, When i click the post goods issue in VL02N, I would like to check if the cost of mateial is equal to zero. If it is zero, I would like to stop the transaction with a error message. But in the user exit, I cannot find which field provide the mater

  • Need information on align_cpy_1 function

    Hi, Our application crached with a SIGBUS error when executing memcpy(). When we run debugger on the core file, the end of stack shows a call to align_cpy_1. From our code we call memcpy() to copy 8088 bytes. but the stack shows align_cpy_1 with the

  • I want to save large pdf files from my computer to my iPad so I can view them in Adobe Reader.

    I want to save large pdf files from my computer to my iPad so I can view them in Adobe Reader. I do not want to view them in iBooks or Quickoffice. Since I cannot email these large files, how can I get them on my iPad? Thanks for your help.

  • Non breaking space

    Does anyone know how to do the equivalent of MS word's non breaking space. trying to use this to keep things like phone numbers (with embedded spaces) from being split across 2 lines when using dynamic templates.

  • Internal Software Error occured in MIG

    PC起動直後.CreateTaskを実行した時に[Rc:-229665(Internal Software Error Occured in MIG software. Please contact National Instruments Support.) が発生します.これはどの様な場合に起きるのでしょうか.原因と対策を教えて下さい.宜しくお願いします.​また.環境は以下の通りです.   OS:WinXP SP2(日本語)   DaqMx:8.6