我们可以测量一个函数所用的时间 JAVA 借助于 JAVAlang.System。currentTimeMillis() 方法此方法以毫秒为单位返回当前时间。我们可以在函数的开头和结尾调用这个方法,并通过差值来度量函数所花费的时间。
null
import java.io.*; public class Time { public static void main(String[] args) { // starting time long start = System.currentTimeMillis(); // start of function count_function( 10000000 ); // end of function // ending time long end = System.currentTimeMillis(); System.out.println( "Counting to 10000000 takes " + (end - start) + "ms" ); } // A dummy function that runs a loop x times public static void count_function( long x) { System.out.println( "Loop starts" ); for ( long i = 0 ; i < x; i++) ; System.out.println( "Loop ends" ); } } |
输出:
Loop starts Loop ends Counting to 10000000 takes 8ms
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END