2011-11-24 28 views
74

Có đồng hồ bấm giờ trong Java không? Bởi vì trên google tôi chỉ tìm thấy mã của đồng hồ bấm giờ và họ không làm việc, họ cho tôi luôn luôn 0 mili giây.Có đồng hồ bấm giờ trong Java không?

Mã này mà tôi thấy không hoạt động nhưng tôi không thấy lý do vì mã này có vẻ ổn với tôi.

public class StopWatch { 

    private long startTime = 0; 
    private long stopTime = 0; 
    private boolean running = false; 


    public void start() { 
    this.startTime = System.currentTimeMillis(); 
    this.running = true; 
    } 


    public void stop() { 
    this.stopTime = System.currentTimeMillis(); 
    this.running = false; 
    } 


    //elaspsed time in milliseconds 
    public long getElapsedTime() { 
    long elapsed; 
    if (running) { 
     elapsed = (System.currentTimeMillis() - startTime); 
    } else { 
     elapsed = (stopTime - startTime); 
    } 
    return elapsed; 
    } 


    //elaspsed time in seconds 
    public long getElapsedTimeSecs() { 
    long elapsed; 
    if (running) { 
     elapsed = ((System.currentTimeMillis() - startTime)/1000); 
    } else { 
     elapsed = ((stopTime - startTime)/1000); 
    } 
    return elapsed; 
    } 
} 
+10

Và làm thế nào để bạn determin nó đã không làm việc? (có lẽ bạn đang đo lường một cái gì đó mà mất ít thời gian để thực hiện hơn so với tính chính xác của System.currentTimeMillis()) – nos

+5

Xin vui lòng gửi mã như thế nào bạn đang thử nghiệm lớp này ... – DXTR66

+1

Chỉ muốn lưu ý rằng đây là một trong những câu hỏi sách giáo khoa trong "Giới thiệu về Lập trình Java, Phiên bản toàn diện (ấn bản lần thứ 9)". – Sam

Trả lời

66

Bạn sẽ tìm thấy một trong

http://commons.apache.org/lang/

Nó được gọi là

org.apache.commons.lang.time.StopWatch 

Nhưng nó khoảng không giống như bạn. Nếu bạn đang ở cho chính xác hơn, sử dụng

System.nanoTime() 

Xem thêm những câu hỏi này ở đây:

Time measuring overhead in Java

66

Sử dụng Guava's Stopwatch class.

Đối tượng đo thời gian trôi qua tính bằng nano giây. Nó rất hữu ích để đo thời gian trôi qua sử dụng lớp này thay vì các cuộc gọi trực tiếp đến System.nanoTime() cho một vài lý do:

  • Một nguồn tin thời gian thay thế có thể được thay thế, để thử nghiệm hoặc hiệu suất lý do.
  • Theo tài liệu của nanoTime, giá trị trả lại không có ý nghĩa tuyệt đối và chỉ có thể được hiểu là có liên quan đến dấu thời gian khác được trả về bởi nanoTime vào một thời điểm khác. Đồng hồ bấm giờ là trừu tượng hiệu quả hơn vì nó chỉ hiển thị những giá trị tương đối này, không phải là giá trị tuyệt đối.
Stopwatch stopwatch = Stopwatch.createStarted(); 
doSomething(); 
stopwatch.stop(); // optional 

long millis = stopwatch.elapsedMillis(); 

log.info("that took: " + stopwatch); // formatted string like "12.3 ms" 
+1

đồng hồ bấm giờ guavas thiếu 'getStartTime()', apache bị thiếu 'isRunning()' ahhhh –

+2

@ToKra Bạn sẽ làm gì với thời gian bắt đầu? Vì nó là thời gian nano, bạn không thể sử dụng nó cho bất cứ điều gì có ý nghĩa anyway, như được mô tả trong tài liệu. – Trejkaz

6

Mã này không hoạt động vì biến trôi qua trong getElapsedTimeSecs() không phải là một phao/đôi.

2

thử

import java.awt.event.*; 

import java.awt.*; 

import javax.swing.*; 

public class millis extends JFrame implements ActionListener, Runnable 
    { 

    private long startTime; 
    private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss.SSS"); 
    private final JButton startStopButton= new JButton("Start/stop"); 
    private Thread updater; 
    private boolean isRunning= false; 
    private final Runnable displayUpdater= new Runnable() 
     { 
     public void run() 
      { 
      displayElapsedTime(System.currentTimeMillis() - millis.this.startTime); 
     } 
    }; 
    public void actionPerformed(ActionEvent ae) 
     { 
     if(isRunning) 
      { 
      long elapsed= System.currentTimeMillis() - startTime; 
      isRunning= false; 
      try 
       { 
       updater.join(); 
       // Wait for updater to finish 
      } 
      catch(InterruptedException ie) {} 
      displayElapsedTime(elapsed); 
      // Display the end-result 
     } 
     else 
      { 
      startTime= System.currentTimeMillis(); 
      isRunning= true; 
      updater= new Thread(this); 
      updater.start(); 
     } 
    } 
    private void displayElapsedTime(long elapsedTime) 
     { 
     startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime))); 
    } 
    public void run() 
     { 
     try 
      { 
      while(isRunning) 
       { 
       SwingUtilities.invokeAndWait(displayUpdater); 
       Thread.sleep(50); 
      } 
     } 
     catch(java.lang.reflect.InvocationTargetException ite) 
      { 
      ite.printStackTrace(System.err); 
      // Should never happen! 
     } 
     catch(InterruptedException ie) {} 
     // Ignore and return! 
    } 
    public millis() 
     { 
     startStopButton.addActionListener(this); 
     getContentPane().add(startStopButton); 
     setSize(100,50); 
     setVisible(true); 
    } 
    public static void main(String[] arg) 
     { 
     new Stopwatch().addWindowListener(new WindowAdapter() 
      { 
      public void windowClosing(WindowEvent e) 
       { 
       System.exit(0); 
      } 
     }); 
     millis s=new millis(); 
     s.run(); 
    } 
} 
22

mùa xuân này cung cấp một StopWatch Lớp thanh lịch.

StopWatch stopWatch = new StopWatch(); 
stopWatch.start(); 
    // Do something 
stopWatch.stop(); 
    System.out.println(stopWatch.getTotalTimeMillis()); 
5

Sử dụng System.currentTimeMillis() để nhận thời gian bắt đầu và thời gian kết thúc và tính chênh lệch.

class TimeTest1 { 
    public static void main(String[] args) { 

    long startTime = System.currentTimeMillis(); 

    long total = 0; 
    for (int i = 0; i < 10000000; i++) { 
     total += i; 
    } 

    long stopTime = System.currentTimeMillis(); 
    long elapsedTime = stopTime - startTime; 
    System.out.println(elapsedTime); 
    } 
} 

More info at this tutorial

0

user1007522, Tôi không biết tại sao mã của bạn không hoạt động (trông giống như đã được nhận xét về điều đó), nhưng tôi chỉ gặp vấn đề tương tự khi nhận được 0 miliseconds từ com.google.common.base.Stopwatch .

tôi đang làm

Stopwatch stopwatch = new Stopwatch(); 
doSomething(); 
logger.info("test took:" + stopwatch); 

Bây giờ tôi đang làm

Stopwatch stopwatch = new Stopwatch().start(); 
doSomething(); 
stopwatch.stop(); 
logger.info("test took:" + stopwatch); 

và nó hoạt động, tôi nhận được "thử nghiệm mất: 26,81 s"

1

Hãy thử điều này:

/* 
* calculates elapsed time in the form hrs:mins:secs 
*/ 
public class StopWatch 
{ 
    private Date startTime; 

    public void startTiming() 
    { 
     startTime = new Date(); 
    } 

    public String stopTiming() 
    { 
     Date stopTime = new Date(); 
     long timediff = (stopTime.getTime() - startTime.getTime())/1000L; 
     return(DateUtils.formatElapsedTime(timediff)); 
    } 

} 

Sử dụng:

StopWatch sw = new StopWatch(); 
... 
sw.startTiming(); 
... 
String interval = sw.stopTiming(); 
+2

DateUtils là một phần của Apache Commons, tại sao không chỉ sử dụng StopWatch của họ? –

+0

Trong hầu hết các trường hợp, bạn sẽ sử dụng một số thư viện phổ biến như được đề cập trong các câu trả lời khác (ví dụ: Apache Commons). Bạn thậm chí có thể chỉ lấy một phần của thư viện nếu bạn không cần mọi thứ. – guyarad

4

Không có tiện ích Đồng hồ bấm giờ nào được xây dựng nhưng với JSR-310 (Java 8 Time), bạn có thể thực hiện việc này đơn giản.

ZonedDateTime now = ZonedDateTime.now(); 
// Do stuff 
long seconds = now.until(ZonedDateTime.now(), ChronoUnit.SECONDS); 

Tôi chưa đánh giá chính xác điều này nhưng tôi đoán sử dụng đồng hồ bấm giờ của Guava hiệu quả hơn.

25

Bây giờ bạn có thể thử một cái gì đó như:

Instant starts = Instant.now(); 
Thread.sleep(10); 
Instant ends = Instant.now(); 
System.out.println(Duration.between(starts, ends)); 

Output là trong ISO 8601.

+1

Nhanh chóng và dễ dàng, cảm ơn bạn rất nhiều! Giúp theo dõi thời gian tác vụ ngay từ đầu. – ndm13

2

Simple ra khỏi lớp hộp Stopwatch:

import java.time.Duration; 
import java.time.Instant; 

public class StopWatch { 

    Instant startTime, endTime; 
    Duration duration; 
    boolean isRunning = false; 

    public void start() { 
     if (isRunning) { 
      throw new RuntimeException("Stopwatch is already running."); 
     } 
     this.isRunning = true; 
     startTime = Instant.now(); 
    } 

    public Duration stop() { 
     this.endTime = Instant.now(); 
     if (!isRunning) { 
      throw new RuntimeException("Stopwatch has not been started yet"); 
     } 
     isRunning = false; 
     Duration result = Duration.between(startTime, endTime); 
     if (this.duration == null) { 
      this.duration = result; 
     } else { 
      this.duration = duration.plus(result); 
     } 

     return this.getElapsedTime(); 
    } 

    public Duration getElapsedTime() { 
     return this.duration; 
    } 

    public void reset() { 
     if (this.isRunning) { 
      this.stop(); 
     } 
     this.duration = null; 
    } 
} 

Cách sử dụng:

StopWatch sw = new StopWatch(); 
sw.start(); 
    // doWork() 
sw.stop(); 
System.out.println(sw.getElapsedTime().toMillis() + "ms"); 
0

Hãy thử điều này.

public class StopWatch { 

     private long startTime = 0; 
     private long stopTime = 0; 

     public StopWatch() 
     { 
      startTime = System.currentTimeMillis(); 
     } 

     public void start() { 
     startTime = System.currentTimeMillis(); 
     } 

     public void stop() { 
     stopTime = System.currentTimeMillis(); 
     System.out.println("StopWatch: " + getElapsedTime() + " milliseconds."); 
     System.out.println("StopWatch: " + getElapsedTimeSecs() + " seconds."); 
     } 

     /** 
     * @param process_name 
     */ 
     public void stop(String process_name) { 
      stopTime = System.currentTimeMillis(); 
      System.out.println(process_name + " StopWatch: " + getElapsedTime() + " milliseconds."); 
      System.out.println(process_name + " StopWatch: " + getElapsedTimeSecs() + " seconds."); 
     }  

     //elaspsed time in milliseconds 
     public long getElapsedTime() { 
      return stopTime - startTime; 
     } 

     //elaspsed time in seconds 
     public double getElapsedTimeSecs() { 
     double elapsed; 
      elapsed = ((double)(stopTime - startTime))/1000; 
     return elapsed; 
     } 
} 

Cách sử dụng:

StopWatch watch = new StopWatch(); 
// do something 
watch.stop(); 

Console:

StopWatch: 143 milliseconds. 
StopWatch: 0.143 seconds. 
0

sử dụng: com.google.common.base.Stopwatch, nó đơn giản và dễ dàng.

<dependency> 
<groupId>com.google.guava</groupId> 
<artifactId>guava</artifactId> 
<version>23.0</version> 
</dependency> 

dụ:

Stopwatch stopwatch = new Stopwatch(); 
stopwatch.start(); 

"Do something" 

logger.debug("this task took " + stopwatch.stop().elapsedTime(TimeUnit.MILLISECONDS) + " mills"); 

nhiệm vụ này mất 112 nhà máy

Các vấn đề liên quan