这是我看到的一种模式,感觉挺实用的。可以用于监控任意代码的执行时间,比直接使用 System.currentTimeMillis() 稍微优雅一点点。
Stopwatch 是 guava 包中的工具类。
示例代码如下:
log.info("begin to execute sql: {}", sql);
Stopwatch stopwatch = Stopwatch.createStarted();
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
// deal with resultSet
}
log.info("end to execute sql. cost:{} ms.", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
