Is this the best way to measure the speed of an input stream?

Hi guys,
I have written the following method to read the source of a web page. I have added the functionality to calculate the speed.
public StringBuffer read(String url)
        int lc = 0;
        long lastSpeed = System.currentTimeMillis();
        //string buffer for reading in the characters
        StringBuffer buffer = new StringBuffer();
        try
            //try to set URL
            URL URL = new URL(url);
            //create input streams
            InputStream content = (InputStream) URL.getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            //in line
            String line;
            //while still reading in
            while ((line = in.readLine()) != null)
                lc++;
                if ((lc % _Sample_Rate) == 0)
                    this.setSpeed(System.currentTimeMillis() - lastSpeed);
                    lastSpeed = System.currentTimeMillis();
                //add character to string buffer
                buffer.append(line);
        //catch errors
        catch (MalformedURLException e)
            System.out.println("Invalid URL - " + e);
        catch (IOException e)
            System.out.println("Invalid URL - " + e);
        //return source
        return buffer;
    }Is it faster to read bytes rather than characters?
This method is a very important part of my project and must be as quick as possible.
Any ideas on how I can make it quicker? Is my approach to calculating the speed the best way to it?
Any help/suggestions would be great.
thanks
alex

sigh
reading bytes might be slightly faster than reading chars, since you don't have to do the conversion and you don't have to make String objects. Certainly, you don't want to use readLine. If you're using a reader, use read(buf, length, offset)
My suggestion:
Get your inputstream, put a bufferedInputStream over it, and use tje loadAll method from my IOUtils class.
IOUtils is given freely, but please do not change its package or submit this as your own work.
====
package tjacobs;
import java.awt.Component;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
public class IOUtils {
     public static final int DEFAULT_BUFFER_SIZE = (int) Math.pow(2, 20); //1 MByte
     public static final int DEFAULT_WAIT_TIME = 30 * 1000; // 30 Seconds
     public static final int NO_TIMEOUT = -1;
     public static final boolean ALWAYS_BACKUP = false;
     public static String loadTextFile(File f) throws IOException {
          BufferedReader br = new BufferedReader(new FileReader(f));
          char data[] = new char[(int)f.length()];
          int got = 0;
          do {
               got += br.read(data, got, data.length - got);
          while (got < data.length);
          return new String(data);
     public static class TIMEOUT implements Runnable {
          private long mWaitTime;
          private boolean mRunning = true;
          private Thread mMyThread;
          public TIMEOUT() {
               this(DEFAULT_WAIT_TIME);
          public TIMEOUT(int timeToWait) {
               mWaitTime = timeToWait;
          public void stop() {
               mRunning = false;
               mMyThread.interrupt();
          public void run () {
               mMyThread = Thread.currentThread();
               while (true) {
                    try {
                         Thread.sleep(mWaitTime);
                    catch (InterruptedException ex) {
                         if (!mRunning) {
                              return;
     public static InfoFetcher loadData(InputStream in) {
          byte buf[] = new byte[DEFAULT_BUFFER_SIZE]; // 1 MByte
          return loadData(in, buf);
     public static InfoFetcher loadData(InputStream in, byte buf[]) {
          return loadData(in, buf, DEFAULT_WAIT_TIME);
     public static InfoFetcher loadData(InputStream in, byte buf[], int waitTime) {
          return new InfoFetcher(in, buf, waitTime);
     public static String loadAllString(InputStream in) {
          InfoFetcher fetcher = loadData(in);
          fetcher.run();
          return new String(fetcher.buf, 0, fetcher.got);
     public static byte[] loadAll(InputStream in) {
          InfoFetcher fetcher = loadData(in);
          fetcher.run();
          byte bytes[] = new byte[fetcher.got];
          for (int i = 0; i < fetcher.got; i++) {
               bytes[i] = fetcher.buf;
          return bytes;
     public static class PartialReadException extends RuntimeException {
          public PartialReadException(int got, int total) {
               super("Got " + got + " of " + total + " bytes");
     public static class InfoFetcher implements Runnable {
          public byte[] buf;
          public InputStream in;
          public int waitTime;
          private ArrayList mListeners;
          public int got = 0;
          protected boolean mClearBufferFlag = false;
          public InfoFetcher(InputStream in, byte[] buf, int waitTime) {
               this.buf = buf;
               this.in = in;
               this.waitTime = waitTime;
          public void addInputStreamListener(InputStreamListener fll) {
               if (mListeners == null) {
                    mListeners = new ArrayList(2);
               if (!mListeners.contains(fll)) {
                    mListeners.add(fll);
          public void removeInputStreamListener(InputStreamListener fll) {
               if (mListeners == null) {
                    return;
               mListeners.remove(fll);
          public byte[] readCompletely() {
               run();
               return buf;
          public int got() {
               return got;
          public void run() {
               if (waitTime > 0) {
                    TIMEOUT to = new TIMEOUT(waitTime);
                    Thread t = new Thread(to);
                    t.start();
               int b;
               try {
                    while ((b = in.read()) != -1) {
                         if (got + 1 > buf.length) {
                              buf = expandBuf(buf);
                         buf[got++] = (byte) b;
                         int available = in.available();
                         if (got + available > buf.length) {
                              buf = expandBuf(buf);
                         got += in.read(buf, got, available);
                         signalListeners(false);
                         if (mClearBufferFlag) {
                              mClearBufferFlag = false;
                              got = 0;
               } catch (IOException iox) {
                    throw new PartialReadException(got, buf.length);
               } finally {
                    buf = trimBuf(buf, got);
                    signalListeners(true);
          private void setClearBufferFlag(boolean status) {
               mClearBufferFlag = status;
          public void clearBuffer() {
               setClearBufferFlag(true);
          private void signalListeners(boolean over) {
               if (mListeners != null) {
                    Iterator i = mListeners.iterator();
                    InputStreamEvent ev = new InputStreamEvent(got, buf);
                    //System.out.println("got: " + got + " buf = " + new String(buf, 0, 20));
                    while (i.hasNext()) {
                         InputStreamListener fll = (InputStreamListener) i.next();
                         if (over) {
                              fll.gotAll(ev);
                         } else {
                              fll.gotMore(ev);
     public static interface InputStreamListener {
          public void gotMore(InputStreamEvent ev);
          public void gotAll(InputStreamEvent ev);
     public static class InputStreamEvent {
          public int totalBytesRetrieved;
          public byte buffer[];
          public InputStreamEvent (int bytes, byte buf[]) {
               totalBytesRetrieved = bytes;
               buffer = buf;
          public int getBytesRetrieved() {
               return totalBytesRetrieved;
          public byte[] getBytes() {
               return buffer;
     public static void copyBufs(byte src[], byte target[]) {
          int length = Math.min(src.length, target.length);
          for (int i = 0; i < length; i++) {
               target[i] = src[i];
     public static byte[] expandBuf(byte array[]) {
          int length = array.length;
          byte newbuf[] = new byte[length *2];
          copyBufs(array, newbuf);
          return newbuf;
     public static byte[] trimBuf(byte[] array, int size) {
          byte[] newbuf = new byte[size];
          for (int i = 0; i < size; i++) {
               newbuf[i] = array[i];
          return newbuf;

Similar Messages

  • HT1198 I shared disk space and my iPhoto library as described in this article. When creating the disk image, I thought I had set aside enough space to allow for growth (50G). I'm running out of space. What's the best way to increase the disk image size?

    I shared disk space and my iPhoto library as described in this article. When creating the disk image, I thought I had set aside enough space to allow for growth (50G). I'm running out of space. What's the best way to increase the disk image size?

    Done. Thank you, Allan.
    The sparse image article you sent a link to needs a little updating (or there's some variability in prompts (no password was required) with my OS and/or Disk Utility version), but it worked.
    Phew! It would have been much more time consuming to use Time Machine to recover all my photos after repartitioning the drive. 

  • I have lightroom 5.7. Now I have apple TV to connect my Mac to the TV scree. I wish to do a slide show on the TV. However, on the Mac, using ITunes to share photos with the TV, I cannot locate all photo files. What is the best way to save the slide show a

    I have lightroom 5.7. Now I have apple TV to connect my Mac to the TV scree. I wish to do a slide show on the TV. However, on the Mac, using ITunes to share photos with the TV, I cannot locate all photo files. What is the best way to save the slide show and put it where the Mac sharing can find it? So far, I made on one folder in Lightroom, put some photos there and I found them easily. Can this be done with a slide show? Please help quickly! Also worried that the photos I put on the new folder are hard to find afterwards, when the show is done. Where do they go when I delete from from the new folder?I am not alone

    Not that I'm aware of. You just export JPEG copies to a folder that you can point iTunes to. For instance, I have created a folder in my Pictures folder called Apple TV. And within that folder I have other folders of pictures that I can choose from in iTunes to share with Apple TV. But there doesn't seem to be any way to share a Lightroom slideshow. If you have laid to create a video file that would probably work. Apple TV is a little clunky in my opinion. Some things are a little more difficult to do now than they were a while back. I probably haven't provided you with much help, but just keep experimenting and I think you will figure it out.

  • Iphone 4s coming friday, what is the best way to get the notes content from iphone 4 to 4s without doing a restore? i want the new phone to be totally new but not sure how to get notes content across.

    What is the best way to get the notes content from iphone 4 to 4s without doing a restore? i want the new phone to be totally new but not sure how to get notes content across. If I do a restore as I have when previously from one iphone to another it has shown (in settings, usage) the cumulative usage from previous phones so all the hours of calls on all previous iphones will be displayed even though its brand new. Anyone know how I can get my notes (from standard iphone notes app) to my new iphone 4s without restoring from previous iphone 4. Thanks for any help offered.

    First, if you haven't updated to iTunes 10.5, please update now as you will need it for the iPhone 4S and iOS 5.
    Once you're done installing iTunes 10.5, open it. Connect your iPhone to iTunes using the USB cable. Once your iPhone pops up right click on it. For example: an iPhone will appear and it will say "Ryan's iPhone."
    Right click on it and select "Backup" from the dropdown menu. It will start backing up. This should backup your notes.
    Please tell me if you have any problems with backing up.
    Once you backup and get your iPhone 4S, you must follow these steps. If you don't follow these steps, you will not be able to get your notes on your new iPhone 4S.
    Open up iTunes again then right click on your device (iPhone 4S). Once you do you will see a dropdown menu. It will say "Restore from Backup..." Select this and it'll ask for a backup, select it from the dropdown menu. For example "Ryan's iPhone - October 12, 2011." Pick that and it will restore to your backup. Do this when you get your iPhone 4S so you will not lose anything. Even though you're restoring, you're getting back, since you're getting the previous settings, notes, contacts, mail and other settings from your old iPhone. You'll still have Siri though! So, restore when you first get it. Also frequently backup your device, as it will be worth it. You can restore from a backup if something goes wrong or save your data for a future update.
    Once you do that, you should have your notes on your new iPhone 4S and iOS 5.
    Please tell me if you need any help.
    I hoped I answered your questions and solved your problem!

  • Hi I would like to show a presentation written on my macbook air on my television what is the best way to connect the two ?

    Hi I would like to show a presentation written on my macbook air on my television what is the best way to connect the two ?

    Much depends on the available connectivity  of your television.
    If it has HDMI input available, all you will need is a minidisplayport to HDMI adapter, and an HDMI cable long enough to place the Mac in the desired proximity to the TV. The adapter is avaialble from the Apple Store online.
    Provided the HDMI input on the television supports sound, and the model of your MBA supports it as well, make suree that your adapter is also supportive of sound, otherwise you will need to run separate cabling from the headphone jack of the MBA to TV sound input or external speakers.
    This is a somewhat specific answer to a question without any requisite detail. You don't indicate the model or type of inputs on your TV, nor do you indicate the model/generation of MBA you have.

  • What is the best way to get the new iPhone/ iPhone 5

    What is the best way to get the new iPhone/ iPhone 5 when it is released. I want to get the phone as quick as possible. If i order it on The first day of pre orders will i get it on the same day as the release in stores? I'm on an unlimited data plan with AT&amp;T. Because the new iPhone will most likely have 4 g data will I loose the unlimited plan?

    Apple has not made any announcement.  We are not allowed to speculate on this forum.

  • What is the best way to share the High Res images ...

    What is the best way to share the High Res images on my Nokia Lumia 1020?  My Android friends really want to see the original ~12MB images taken with Nokia Pro Camera?
    -Paul
    Solved!
    Go to Solution.

    if you have the att device, then use your att locker.
    ANYONE can sign up for the att locker here:
    https://locker.att.net/app/#welcome
    even if you do not have ATT service, you should sign up NOW.
    There is an application that is pre-installed to allow for the 1020 to upload the full resolution files to the AT&T locker.
    AND, because they are launching the 1020, they are giving a free upgrade to the account to the 50GB box instead of the 5GB.
    they are doing this for a limited time only, I have created a couple of accounts.
    after you create your account, it will have to be verified. after you check your email and verify the box, log back in and you will see it is only a 5gb account.
    click on "my Account/upgrade" and choose the 50GB and you should see it say FREE under the cost.
    then you can upload the full res pictures and share them that way.
    otherwise, if you are within reach, try Bluetooth transfer.

  • What is the best way to follow the scenario for Out look integration with share point using SAP Gateway?

    1)what is the best way to follow the scenario for Out look integration with share point using SAP Gateway?
    2)workflow concepts for Purchase order?
    3)Email triggering from out look for an approval process of PO? how these scenario can be best implemented with updated functions in Duet Enterprise.

    Hi,
    I do not have much idea on gateway integration with outlook but found out this document GWPAM Workflow Template which can be helpful for you to start with.
    also you may want to post your question in SAP Microsoft Interoperability forum
    Regards,
    Chandra

  • Using Microsoft Exchange to access Gmail (Google Apps for Business) contacts, what is the best way to sync the Corporate Directory?

    Using Microsoft Exchange to access Gmail (Google Apps for Business) contacts, what is the best way to sync the Corporate Directory? For instance, we have 40 staff members and wish to populate each phone with the Gmail profile. Right now we have a third party Android app that does this and copies my contacts to each phone. This is problematic. Any solutions to populate a phone with email and phone contacts? Even it it requires double entry for me...thats ok.

    Oh, I meant Leopard does do more than Tiger Server.
    I don't know enough about Server, even less abut Syncing.
    SL is to new, not enough time to iron out the kinks yet imho.
    One day SL will be better than Leo, but...
    I'd ask over in server...
    http://discussions.apple.com/category.jspa?categoryID=96
    Or perhaps Collaboration Services...
    http://discussions.apple.com/forum.jspa?forumID=1352
    They may even have a different opinion on SL.

  • Mac Pro won't start up.  What's the best way to check the power supply?

    Hello. I'm having a severe problem with my 2007 Mac Pro. The symptoms are very easy to describe. The computer apparently shut itself off overnight, and when I press the power button to turn it on, absolutely nothing happens. No lights, no chime, no signs of any power whatsoever in the computer. I have never had major problems with the computer before. (Although I had recently noticed some minor skipping problems with streaming videos and Firefox had started hanging occasionally.)
    So far, I have checked the power cable and the power outlet. I have also reset the SMC (holding in the Power button for 5 seconds with the unit unplugged). I am unable to see any light in the diagnostic LEDs (including LED 1) when I press the DIAG_LED button on the logic board.
    While I welcome other suggestions, all I can figure is that this is either a power supply problem or a major logic board failure, but I don't know which. I have a multimeter and would like to test very directly if the power supply is the problem, because they are very expensive and obviously I do not want to order a replacement supply if it would not fix the computer. Does anyone know what the best way to test the supply directly is? What pins on what cable should I test, and what voltage should I look for?
    Also: No the computer is not under any warranty. If at all possible, I would like to fix this myself. Thanks for any help you can give.

    Well, I may have found the answer to my question as to why replacing the fuse dows not seem to be encouraged. I cut out the failed fuse (fast fuse, ceramic, 16 Amp 250V), and replaced it with another that was as close to it in spec as I could find (15 A instead of 16). Then I put the supply back in the case.
    When I tried to plug it in, I got an immediate spark, followed by an acrid smell from the power supply. Later inspection revealed that the new fuse blew, as did another component nearby (not sure what it was) where I could see blackening and the smell was concentrated. At this point, I would consider myself lucky if the power supply didn't take anything else on the computer out with it.
    Lesson learned; will try a new power supply and go from there.

  • What is the best way to specify the color of a control or indicator?

    What is the best way to command the color of a control or indicator? 
    Can color be programmed within the code?  If so, which versions of LV have this feature?
    Thanks,
    Jeff
    Jeffrey Bledsoe
    Electrical Engineer

    You can change the color of controls and indicators by using the 'color' parameter in a property node.  I believe this has always been possible in LabVIEW.  (At least back to Ver. 4)
    Here is a little example (LV7.1):
    Using LabVIEW: 7.1.1, 8.5.1 & 2013
    Attachments:
    control colors.vi ‏21 KB

  • What is the best way to get the end of record from internal table?

    Hi,
    what is the best way to get the latest year and month ?
    the end of record(KD00011001H 1110 2007  11)
    Not KE00012002H, KA00012003H
    any function for MBEWH table ?
    MATNR                 BWKEY      LFGJA LFMON
    ========================================
    KE00012002H        1210             2005  12
    KE00012002H        1210             2006  12
    KA00012003H        1000             2006  12
    KD00011001H        1110             2005  12
    KD00011001H        1110             2006  12
    KD00011001H        1110             2007  05
    KD00011001H        1110             2007  08
    KD00011001H        1110             2007  09
    KD00011001H        1110             2007  10
    KD00011001H        1110             2007  11
    thank you
    dennis
    Edited by: ogawa Dennis on Jan 2, 2008 1:28 AM
    Edited by: ogawa Dennis on Jan 2, 2008 1:33 AM

    Hi dennis,
    you can try this:
    Sort <your internal_table MBEWH> BY lfgja DESCENDING lfmon DESCENDING.
    Thanks
    William Wilstroth

  • What is the best way to replace the Inline Views for better performance ?

    Hi,
    I am using Oracle 9i ,
    What is the best way to replace the Inline Views for better performance. I see there are lot of performance lacking with Inline views in my queries.
    Please suggest.
    Raj

    WITH plus /*+ MATERIALIZE */ hint can do good to you.
    see below the test case.
    SQL> create table hx_my_tbl as select level id, 'karthick' name from dual connect by level <= 5
    2 /
    Table created.
    SQL> insert into hx_my_tbl select level id, 'vimal' name from dual connect by level <= 5
    2 /
    5 rows created.
    SQL> create index hx_my_tbl_idx on hx_my_tbl(id)
    2 /
    Index created.
    SQL> commit;
    Commit complete.
    SQL> exec dbms_stats.gather_table_stats(user,'hx_my_tbl',cascade=>true)
    PL/SQL procedure successfully completed.
    Now this a normal inline view
    SQL> select a.id, b.id, a.name, b.name
    2 from (select id, name from hx_my_tbl where id = 1) a,
    3 (select id, name from hx_my_tbl where id = 1) b
    4 where a.id = b.id
    5 and a.name <> b.name
    6 /
    Execution Plan
    0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=7 Card=2 Bytes=48)
    1 0 HASH JOIN (Cost=7 Card=2 Bytes=48)
    2 1 TABLE ACCESS (BY INDEX ROWID) OF 'HX_MY_TBL' (TABLE) (Cost=3 Card=2 Bytes=24)
    3 2 INDEX (RANGE SCAN) OF 'HX_MY_TBL_IDX' (INDEX) (Cost=1 Card=2)
    4 1 TABLE ACCESS (BY INDEX ROWID) OF 'HX_MY_TBL' (TABLE) (Cost=3 Card=2 Bytes=24)
    5 4 INDEX (RANGE SCAN) OF 'HX_MY_TBL_IDX' (INDEX) (Cost=1 Card=2)
    Now i use the with with the materialize hint
    SQL> with my_view as (select /*+ MATERIALIZE */ id, name from hx_my_tbl where id = 1)
    2 select a.id, b.id, a.name, b.name
    3 from my_view a,
    4 my_view b
    5 where a.id = b.id
    6 and a.name <> b.name
    7 /
    Execution Plan
    0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=8 Card=1 Bytes=46)
    1 0 TEMP TABLE TRANSFORMATION
    2 1 LOAD AS SELECT
    3 2 TABLE ACCESS (BY INDEX ROWID) OF 'HX_MY_TBL' (TABLE) (Cost=3 Card=2 Bytes=24)
    4 3 INDEX (RANGE SCAN) OF 'HX_MY_TBL_IDX' (INDEX) (Cost=1 Card=2)
    5 1 HASH JOIN (Cost=5 Card=1 Bytes=46)
    6 5 VIEW (Cost=2 Card=2 Bytes=46)
    7 6 TABLE ACCESS (FULL) OF 'SYS_TEMP_0FD9D6967_3C610F9' (TABLE (TEMP)) (Cost=2 Card=2 Bytes=24)
    8 5 VIEW (Cost=2 Card=2 Bytes=46)
    9 8 TABLE ACCESS (FULL) OF 'SYS_TEMP_0FD9D6967_3C610F9' (TABLE (TEMP)) (Cost=2 Card=2 Bytes=24)
    here you can see the table is accessed only once then only the result set generated by the WITH is accessed.
    Thanks,
    Karthick.

  • Can you please tell me the best way to increase the number of the downloads of my free ibook

    Since I got the green light in iBook store my free book has been
    Downloaded about 50 times in 10 days.
    What is the best way to increase the number?
    The title is : monter a cheval
    It's in French
    Thanks for the help

    Do you, or anyone ese, have experience in this service? And how's the paid vs free services they have?

  • What is the best way to update the delivery time?

    Hi All,
    One of the tasks I have in my job is to updste purchase orders with information found in the orderconfirmation we receive. In the order screen, ME22N, you can change the date in the item, where you have all positions listed. But you can also change it in the tab classifications.
    What is the best way to update the delivery time?
    Best Regards
    Praveen

    Hi
    It may userfull to you
    If you change the delivery date after you have send the PO, then the statistical delivery date is still containing the old delivery date., as long the order is not send this date is changed together with the delivery date.
    Vendor evaluation is performed based on statistical delivery date.
    So if you are responsible for a date change, then you change both dates, that the vendor does not get bad points. but if the vendor cannot deliver at the wished dates, then you change the delivery date only, that all people in your company and MRP run can rely on the new delivery date, but your vendor is evaluated against the old date, because of his fault.
    regards
    Madhu

Maybe you are looking for

  • ITunes and CD-Text

    Will Apple ever open iTunes to facilitate CD-Text? I have found scripts for the Mac but nothing for the PC to allow iTunes to use CD-Text. Official Support for it would make sense considering that a great portion of the world's computer users still h

  • XDODTEXE forces output to be UTF-8 ?

    I am using a data template as my XML generation source. The database character set is ISO-8859-1. I have some data that has French characters - accents, graves etc. When I use SQL or PL/SQL to generate the XML, there is no issue - the output contains

  • Nokia C7's display suddenly dims out even in brigh...

    I was using my C7 outdoors(in bright light) when I suddenly noticed that its display had totally dimmed out. Light sensor was not covered with anything. The other functions of the phone were working fine but the display stayed dim for approx 3 minute

  • Adobe Fireworks CS6 'redefine' style isn't working properly

    Hi there. I'm having an issue. So I'm creating some graphics.  I have Three Objects. I've created each object, then saved a style for those objects, saving everything but 'text' styling. I made some adjustments to the linear gradient of 2 of these ob

  • Desktop Manager - Vista

    Hi All, i have a lot of problem with Desktop manager and Windows Vista. I tried sw rev 4.3, 4.22, but i have every time some problem with the connection. Sometime after installation, during the boot of the software it crashed and software was killed