How do I time a method's execution in Java?

前端 未结 30 2744
北荒
北荒 2020-11-21 11:15
  1. How do I get a method\'s execution time?
  2. Is there a Timer utility class for things like timing how long a task takes, etc?

Mos

30条回答
  •  一向
    一向 (楼主)
    2020-11-21 11:41

    I go with the simple answer. Works for me.

    long startTime = System.currentTimeMillis();
    
    doReallyLongThing();
    
    long endTime = System.currentTimeMillis();
    
    System.out.println("That took " + (endTime - startTime) + " milliseconds");
    

    It works quite well. The resolution is obviously only to the millisecond, you can do better with System.nanoTime(). There are some limitations to both (operating system schedule slices, etc.) but this works pretty well.

    Average across a couple of runs (the more the better) and you'll get a decent idea.

提交回复
热议问题