zoukankan      html  css  js  c++  java
  • Java Cookbook-Date and Times

    6.12 Measuring Elapsed Time

      --Problem

        You need to time how long long it takes to do something

      --Solution

        Call System.currentTimeMillis() twice,or System.nanoTime(),and subtract the first

        ressult from the second result

      --Discussion

        The System class contains two static methods for times.currentTimeMillis() return the current time (since 1970) in milliseconds,and nanoTime()

      (new in 1.5) returns the relative time in nanoseconds.To time some event use this:

     

     long start=System.currentTimeMillis();
      method_to_be_timed();
    
      long end=System.currentTimeMillis();
    
      long elapsed=end-start;//time in milliseconds
    
      or:
    
      long start=System.nanoTime();
    
      method_to_be_timed();
    
      long end=System.nanoTime();
    
      long elapsed=end-start;//time in nanoseconds
    

      Here is a short example to measure how long it takes a user to press return.

    We divide the time in milliseconds by 1000 to get seconds

    and print it nicely using a NumberFormat

      long t0,t1;
    
      System.out.println("Press return when ready");
      
      t1=System.currentTimeMillis();
    
      int b;
    
    do{
    
      b=System.in.read();
    
    }while(b!='
    '&&b!='
    ');
    
      t1=System.currrentTimeMillis();
    
      double deltaT=t1-t0;
    
      System.out.println(DecimalFormat.getInstance().format(deltaT/1000.)+"seconds.");
    

     

     import java.io.*;
    
     import java.text.*;
    
    
    
      /**
    
       * Timer for processing sqrt and I/O operations
    
       */
    
      public class TimerCompution{
    
        public static void man(String[] args){
    
          try{
    
            new Timer().run();
        }catch(IOException e){System.err.println(e);}
      } 
    
      public void run()throws IOException{
    
        DataInputStream n=new DataOutputStream(
    
          new BufferedOutputStream(new FileOutputStream(SysDep.getDevNull()));
          long t0,t1;
          System.out.println("Java Starts at "+(t0=System.currentTimeMillis()));
    
          double k;
          for(int i=0;i<100000;i++){
    
            k=2.1*Math.sqrt((dobule)i);
            n.writeDouble(k);
          }
    
         System.out.println("Java Ends at "+(t1=System.currentTimeMillis()));
         double deltaT=t1-t0;
         System.out.println("This run took "+
           DecimalFormat.getInstance().format(deltaT/1000.)+" seconds.");
     }   
    }
    

      

  • 相关阅读:
    linux系统安装mysql数据库
    pyinstaller打包问题
    jmeter-Parameters和Body Data两种方式传参的区别
    jmeter-保存响应到文件
    Jenkins获取运行job的用户信息
    pytest插件(多重校验、用例依赖、执行顺序、失败重跑、重复执行、标记)
    谷歌开发者工具(F12)
    Linux常用命令
    一般什么原因会导致偶现问题?
    Fiddler模拟接口返回进行测试(二)
  • 原文地址:https://www.cnblogs.com/hephec/p/4877140.html
Copyright © 2011-2022 走看看