我们在日常进行Java语言开发时,可能需要监控不同方法的运行时间,知道性能瓶颈在哪。利用springframework框架的工具类StopWatch可以快速方便的查看到每段代码运行的时间,准确确定性能瓶颈所在。
使用StopWatch类也很简单。new出实例,调用该实例的start()和stop()方法即可。如下代码StopWatch stopWatch = new StopWatch();
//房间类型图片
List images = platenoHotelService.getHotelImage(innId, 2);
Map imageUrl = new HashMap<>();
if (images !=null) {
for (ImageData image : images) {
imageUrl.put(image.getRoomTypeCode(), image.getImageUrl());
}
}
//调用酒店房型列表
stopWatch.start("search.getHotelRoomType");
String roomType = platenoHotelService.getHotelRoomType(innId);
stopWatch.stop();
stopWatch.start("search.parseObject");
JSONObject roomTypeList = JSONObject.parseObject(roomType);
JSONArray roomTypeArray = roomTypeList.getJSONObject("data").getJSONArray("roomTypeData");
stopWatch.stop();
List hotelRoomTypeVOList = new ArrayList<>();
stopWatch.start("search.roomTypeArrayForeach");
for (Object roomTypeItem : roomTypeArray) {
JSONObject roomTypeObject = (JSONObject)roomTypeItem;
HotelRoomTypeVO hotelRoom = JSONObject.toJavaObject(roomTypeObject, HotelRoomTypeVO.class);
if(hotelRoom.getValid() == 1) {
RealRoomStatusData realRoomStatusData = platenoHotelService.getHotelRoomInfo(innId, hotelRoom.getRoomTypeCode(), endOfDay, sourceType, days);
if (realRoomStatusData != null) {
hotelRoom.setImageUrl(imageUrl.get(hotelRoom.getRoomTypeCode()));
hotelRoom.setRealRoomStatusData(realRoomStatusData);
hotelRoomTypeVOList.add(hotelRoom);
}
}
}
stopWatch.stop();
logger.info("[酒店房型列表耗时:]" + stopWatch.prettyPrint());
为了查看结果,调用prettyPrint()方法即可,下图就是上面示例的运行结果。可以看出总花费时间6062ms。三列分别为监控代码段的花费时间(毫秒)、百分比、名称。可以很直观看出每段代码的运行时间以及所占比分比,帮助我们快速找到主要性能问题。