如果我們要測試一個類的方法的執(zhí)行時間,通常我們會這樣做:
- public class TestObject {
-
-
-
- public static void testMethod(){
- for(int i=0; i<100000000; i++){
-
- }
- }
-
-
-
- public void testTime(){
- long begin = System.currentTimeMillis();
- testMethod();
- long end = System.currentTimeMillis();
- System.out.println("[use time]:" + (end - begin));
- }
-
- public static void main(String[] args) {
- TestObject test=new TestObject();
- test.testTime();
- }
- }
大家看到了testTime()方法,就只有"http://測試方法"是需要改變的,下面我們來做一個函數(shù)實(shí)現(xiàn)相同功能但更靈活:
首先定一個回調(diào)接口:
- public interface CallBack {
-
- void execute();
- }
然后再寫一個工具類:
- public class Tools {
-
-
-
-
-
- public void testTime(CallBack callBack) {
- long begin = System.currentTimeMillis();
- callBack.execute();
- long end = System.currentTimeMillis();
- System.out.println("[use time]:" + (end - begin));
- }
-
- public static void main(String[] args) {
- Tools tool = new Tools();
- tool.testTime(new CallBack(){
-
- public void execute(){
-
- TestObject.testMethod();
- }
- });
- }
-
- }
posted on 2008-04-01 12:40
周銳 閱讀(962)
評論(0) 編輯 收藏 所屬分類:
Java