Bạn cũng có thể thử Perf4J. Đó là một cách gọn gàng để làm những gì bạn đang tìm kiếm và giúp thống kê hiệu suất tổng hợp như trung bình, tối thiểu, tối đa, độ lệch chuẩn và giao dịch mỗi giây trong một khoảng thời gian đã định. Một chiết xuất từ http://perf4j.codehaus.org/devguide.html:
StopWatch stopWatch = new LoggingStopWatch();
try {
// the code block being timed - this is just a dummy example
long sleepTime = (long)(Math.random() * 1000L);
Thread.sleep(sleepTime);
if (sleepTime > 500L) {
throw new Exception("Throwing exception");
}
stopWatch.stop("codeBlock2.success", "Sleep time was < 500 ms");
} catch (Exception e) {
stopWatch.stop("codeBlock2.failure", "Exception was: " + e);
}
Output:
INFO: start[1230493236109] time[447] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493236719] time[567] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493237286] time[986] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493238273] time[194] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493238467] time[463] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493238930] time[310] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239241] time[610] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493239852] time[84] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239937] time[30] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239968] time[852] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
nó thực sự phải là nanoTime thực sự – Eugene
Không nên là nanoTime. Xem câu trả lời của rhu. – fabspro
Có một số lý do cụ thể mà bạn đã sử dụng "cuối cùng" ở đây không? Điều gì sẽ khác nếu bạn từ chối từ khóa đó? – dijxtra