Java/Development Class/Timing

Материал из Java эксперт
Перейти к: навигация, поиск

Class for program event timing

   
/*
 * This code is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public 
 * License as published by the Free Software Foundation; either 
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public 
 * License along with this program; if not, write to the Free 
 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
 * MA  02111-1307, USA.
 */
//package no.geosoft.cc.util;

import java.util.Date;

/**
 * Class for program event timing.
 * Usage:
 *
 *   <pre>
 *   Timer timer = new Timer();
 *
 *   // do stuff
 *
 *   System.out.println (timer);  // prints time elapsed since
 *                                // object was created.
 *   </pre>
 * 
 * @author 
 */
public class Timer
{
  private Date  start_;
  
  
  /**
   * Start timer.
   */
  public Timer()
  {
    reset();
  }

  
  /**
   * Returns exact number of milliseconds since timer was started.
   * 
   * @return  Number of milliseconds since timer was started.
   */
  public long getTime()
  {
    Date now = new Date();
    long nMillis = now.getTime() - start_.getTime();
    return nMillis;
  }

  
  /**
   * Restarts the timer.
   */
  public void reset()
  {
    start_ = new Date();  // now    
  }

  
  /**
   * Returns a formatted string showing the elaspsed time
   * suince the instance was created.
   * 
   * @return  Formatted time string.
   */
  public String toString()
  {
    long nMillis = getTime();
    
    long nHours   = nMillis / 1000 / 60 / 60;
    nMillis -= nHours * 1000 * 60 * 60;
      
    long nMinutes = nMillis / 1000 / 60;
    nMillis -= nMinutes * 1000  * 60;
    long nSeconds = nMillis / 1000;
    nMillis -= nSeconds * 1000;
    
    StringBuffer time = new StringBuffer();
    if (nHours > 0) time.append (nHours + ":");
    if (nHours > 0 && nMinutes < 10) time.append ("0");
    time.append (nMinutes + ":");
    if (nSeconds < 10) time.append ("0");
    time.append (nSeconds);
    time.append (".");
    if (nMillis < 100) time.append ("0");
    if (nMillis <  10) time.append ("0");
    time.append (nMillis);
    
    return time.toString();
  }

  
  /**
   * Testing this class.
   * 
   * @param args  Not used.
   */
  public static void main (String[] args)
  {
    Timer timer = new Timer();
    for (int i = 0; i < 100000000; i++) {
      double b = 998.43678;
      double c = Math.sqrt (b);
    }
    System.out.println (timer);
  }
}





Compute and display elapsed time of an operation

   
public class Main {
  public static void main(String[] args) throws Exception{
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 10; i++) {
        Thread.sleep(60);
    }
    long endTime = System.currentTimeMillis();
    float seconds = (endTime - startTime) / 1000F;
    System.out.println(Float.toString(seconds) + " seconds.");
  }
}
//0.625 seconds.





Get elapsed time in days

  
public class Main {
  public static void main(String[] argv) throws Exception {
    long start = System.currentTimeMillis();
    Thread.sleep(2000);
    // Get elapsed time in milliseconds
    long elapsedTimeMillis = System.currentTimeMillis() - start;
    float elapsedTimeDay = elapsedTimeMillis/(24*60*60*1000F);
    System.out.println(elapsedTimeDay);
  }
}





Get elapsed time in hours

  
public class Main {
  public static void main(String[] argv) throws Exception {
    long start = System.currentTimeMillis();
    Thread.sleep(2000);
    // Get elapsed time in milliseconds
    long elapsedTimeMillis = System.currentTimeMillis() - start;
    
    // Get elapsed time in hours
    float elapsedTimeHour = elapsedTimeMillis/(60*60*1000F);
    System.out.println(elapsedTimeHour);
  }
}





Get elapsed time in milliseconds

  
public class Main {
  public static void main(String[] argv) throws Exception {
    long start = System.currentTimeMillis();
    Thread.sleep(2000);
    long elapsedTimeMillis = System.currentTimeMillis() - start;
    System.out.println(elapsedTimeMillis);
  }
}





Get elapsed time in minutes

  

public class Main {
  public static void main(String[] argv) throws Exception {
    long start = System.currentTimeMillis();
    Thread.sleep(2000);
    // Get elapsed time in milliseconds
    long elapsedTimeMillis = System.currentTimeMillis() - start;
    
    // Get elapsed time in minutes
    float elapsedTimeMin = elapsedTimeMillis/(60*1000F);
    System.out.println(elapsedTimeMin);
  }
}





Get elapsed time in seconds

  
public class Main {
  public static void main(String[] argv) throws Exception {
    long start = System.currentTimeMillis();
    Thread.sleep(2000);
    // Get elapsed time in milliseconds
    long elapsedTimeMillis = System.currentTimeMillis() - start;
    
    float elapsedTimeSec = elapsedTimeMillis/1000F;
    System.out.println(elapsedTimeSec);
  }
}





Get seconds since

   
/**
 *  BlueCove - Java library for Bluetooth
 *  Copyright (C) 2006-2008 Vlad Skarzhevskyy
 * 
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 *  @author vlads
 *  @version $Id: TimeUtils.java 2655 2008-12-24 16:04:37Z skarzhevskyy $
 */
import java.util.Calendar;
import java.util.Date;
/**
 * 
 */
public abstract class TimeUtils {
  private static Calendar singleCalendar;
  private static Date singleDate;
  public static String secSince(long start) {
    if (start == 0) {
      return "n/a";
    }
    long msec = since(start);
    long sec = msec / 1000;
    long min = sec / 60;
    sec -= min * 60;
    long h = min / 60;
    min -= h * 60;
    StringBuffer sb;
    sb = new StringBuffer();
    if (h != 0) {
      sb.append(StringUtils.d00((int) h)).append(":");
    }
    if ((h != 0) || (min != 0)) {
      sb.append(StringUtils.d00((int) min)).append(":");
    }
    sb.append(StringUtils.d00((int) sec));
    if ((h == 0) && (min == 0)) {
      sb.append(" sec");
    }
    if ((h == 0) && (min == 0) && (sec <= 1)) {
      msec -= 1000 * sec;
      sb.append(" ");
      sb.append(StringUtils.d000((int) msec));
      sb.append(" msec");
    }
    return sb.toString();
  }
  public static long since(long start) {
    if (start == 0) {
      return 0;
    }
    return (System.currentTimeMillis() - start);
  }
  public static String bps(long size, long start) {
    long duration = TimeUtils.since(start);
    if (duration == 0) {
      return "n/a";
    }
    long bps = ((1000 * 8 * size) / (duration));
    return StringUtils.formatLong(bps) + " bit/s";
  }
  public static String timeNowToString() {
    StringBuffer sb = new StringBuffer();
    appendTime(sb, System.currentTimeMillis(), false);
    return sb.toString();
  }
  public static String timeStampNowToString() {
    StringBuffer sb = new StringBuffer();
    appendTime(sb, System.currentTimeMillis(), true);
    return sb.toString();
  }
  public static StringBuffer appendTimeStampNow(StringBuffer sb, boolean millisecond) {
    return appendTime(sb, System.currentTimeMillis(), millisecond);
  }
  public static synchronized StringBuffer appendTime(StringBuffer sb, long timeStamp,
      boolean millisecond) {
    if (timeStamp == 0) {
      sb.append("n/a");
      return sb;
    }
    if (singleCalendar == null) {
      singleCalendar = Calendar.getInstance();
      singleDate = new Date();
    }
    singleDate.setTime(timeStamp);
    singleCalendar.setTime(singleDate);
    StringUtils.appendD00(sb, singleCalendar.get(Calendar.HOUR_OF_DAY)).append(":");
    StringUtils.appendD00(sb, singleCalendar.get(Calendar.MINUTE)).append(":");
    StringUtils.appendD00(sb, singleCalendar.get(Calendar.SECOND));
    if (millisecond) {
      sb.append(".");
      StringUtils.appendD000(sb, singleCalendar.get(Calendar.MILLISECOND));
    }
    return sb;
  }
  public static boolean sleep(long millis) {
    try {
      Thread.sleep(millis);
      return true;
    } catch (InterruptedException e) {
      return false;
    }
  }
}
/**
 * BlueCove - Java library for Bluetooth Copyright (C) 2006-2008 Vlad
 * Skarzhevskyy
 * 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 * @author vlads
 * @version $Id: StringUtils.java 2655 2008-12-24 16:04:37Z skarzhevskyy $
 */
class StringUtils {
  public static boolean isStringSet(String str) {
    return ((str != null) && (str.length() > 0));
  }
  /**
   * String.equalsIgnoreCase() was added only Since CLDC-1.1.
   * 
   * @param anotherString
   * @return
   */
  public static boolean equalsIgnoreCase(String s1, String s2) {
    if ((s1 == null) || (s2 == null)) {
      return false;
    }
    return (s1.length() == s2.length()) && (s1.toUpperCase().equals(s2.toUpperCase()));
  }
  public static String d00(int i) {
    if ((i > 9) || (i < 0)) {
      return String.valueOf(i);
    } else {
      return "0" + String.valueOf(i);
    }
  }
  public static StringBuffer appendD00(StringBuffer sb, int i) {
    if ((i > 9) || (i < 0)) {
      sb.append(String.valueOf(i));
    } else {
      sb.append("0").append(String.valueOf(i));
    }
    return sb;
  }
  public static String d000(int i) {
    if ((i > 99) || (i < 0)) {
      return String.valueOf(i);
    } else if (i > 9) {
      return "0" + String.valueOf(i);
    } else {
      return "00" + String.valueOf(i);
    }
  }
  public static StringBuffer appendD000(StringBuffer sb, int i) {
    if ((i > 99) || (i < 0)) {
      sb.append(String.valueOf(i));
    } else if (i > 9) {
      sb.append("0").append(String.valueOf(i));
    } else {
      sb.append("0").append("0").append(String.valueOf(i));
    }
    return sb;
  }
  public static String d0000(int i) {
    if ((i > 999) || (i < 0)) {
      return String.valueOf(i);
    } else if (i > 99) {
      return "00" + String.valueOf(i);
    } else if (i > 9) {
      return "00" + String.valueOf(i);
    } else {
      return "000" + String.valueOf(i);
    }
  }
  public static String formatLong(long l) {
    if (l < 1000) {
      return Long.toString(l);
    }
    long l1K = (l / 1000);
    if (l1K < 1000) {
      return Long.toString(l1K) + "," + StringUtils.d000((int) (l - 1000L * l1K));
    } else {
      long l1M = (l1K / 1000);
      return Long.toString(l1M) + "," + StringUtils.d000((int) (l1K - 1000L * l1M)) + ","
          + StringUtils.d000((int) (l - 1000L * l1K));
    }
  }
  public static String toHex00String(int c) {
    String s = Integer.toHexString(c);
    if (s.length() == 1) {
      return "0" + s;
    } else {
      return s;
    }
  }
  public static String padRight(String str, int length, char c) {
    int l = str.length();
    if (l >= length) {
      return str;
    }
    StringBuffer sb = new StringBuffer();
    sb.append(str);
    for (int i = l; i < length; i++) {
      sb.append(c);
    }
    return sb.toString();
  }
  public static char printable(char c) {
    if (c < " ") {
      return " ";
    } else {
      return c;
    }
  }
  public static String toBinaryText(StringBuffer buf) {
    boolean bufHasBinary = false;
    int len = buf.length();
    for (int i = 0; i < len; i++) {
      if (buf.charAt(i) < " ") {
        bufHasBinary = true;
        break;
      }
    }
    if (bufHasBinary) {
      StringBuffer formatedDataBuf = new StringBuffer();
      for (int k = 0; k < len; k++) {
        formatedDataBuf.append(printable(buf.charAt(k)));
      }
      formatedDataBuf.append(" 0x[");
      for (int k = 0; k < len; k++) {
        formatedDataBuf.append(toHex00String(buf.charAt(k))).append(" ");
      }
      formatedDataBuf.append("]");
      buf = formatedDataBuf;
    }
    return buf.toString();
  }
}





Get system time using System class

   
public class Main {
  public static void main(String[] args) {
    long lnSystemTime = System.currentTimeMillis();
    System.out.println("Milliseconds since midnight, January 1, 1970 UTC : " + lnSystemTime);
  }
}





Get time in milliseconds using Java Calendar

   
import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current milliseconds since Jan 1, 1970 are :" + now.getTimeInMillis());
  }
}





java.util.concurrent.TimeUnit: convert between milliseconds and days

  
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
public class Main {
  public static long getDifference(Calendar a, Calendar b, TimeUnit units) {
    return units.convert(b.getTimeInMillis() - a.getTimeInMillis(), TimeUnit.MILLISECONDS);
  }
  public static void main(String[] args) {
    Calendar first = Calendar.getInstance();
    first.set(2008, Calendar.AUGUST, 1);
    Calendar second = Calendar.getInstance();
    System.out.println(getDifference(first, second, TimeUnit.DAYS) + " day(s) between ");
  }
}