public static void main(String[] args) { long a = System.currentTimeMillis(); a=a+1; long b = System.currentTimeMillis()-a; System.out.println("RTun time: " + b + "ms."); }
由于a=a+1执行时间太短,不能直接计算出,只能用间接的方法,这里忽略比较运算所用的时间。 public class Test { private static final long loop = 10000000000; public static void main(String[] args) { long start = System.currentTimeMillis(); for (long a = 0; a < loop; a = a + 1) ; long end = System.currentTimeMillis() - start; System.out.println("Total time: " + end + "ms."); System.out.println("Step time: " + (end * (double) 1000 / loop) + "ns"); } } 我的机器上上面那段程序大约要运行40秒
public static void main(String[] args) { long t0, t1; int a = 0; t0 = System.nanoTime(); a = a + 1; t1 = System.nanoTime(); System.out.println(t1 - t0 + " ns"); } 我机器上的结果是:2000纳秒左右。使用系统纳秒级计算,但是这样的结果很不准确,因为System.nanoTime();这句执行也是需要时间的。像楼上的那样改进一下:public static void main(String[] args) { long t0, t1; t0 = System.nanoTime(); for(int a = 0; a < Integer.MAX_VALUE; a = a + 1); t1 = System.nanoTime(); System.out.println((t1 - t0)/(double)Integer.MAX_VALUE + " ns"); } 这样子,我机器上的输出平均值基本上在1.7纳秒左右摆动。上面这个例子中,循环执行次数越多,所平均下来的时间就越小,在我的机器上1.7纳秒是极限值了。
long a = System.currentTimeMillis();
a=a+1;
long b = System.currentTimeMillis()-a;
System.out.println("RTun time: " + b + "ms.");
}
public class Test {
private static final long loop = 10000000000; public static void main(String[] args) {
long start = System.currentTimeMillis();
for (long a = 0; a < loop; a = a + 1)
;
long end = System.currentTimeMillis() - start;
System.out.println("Total time: " + end + "ms.");
System.out.println("Step time: " + (end * (double) 1000 / loop) + "ns");
}
}
我的机器上上面那段程序大约要运行40秒
long t0, t1;
int a = 0;
t0 = System.nanoTime();
a = a + 1;
t1 = System.nanoTime();
System.out.println(t1 - t0 + " ns");
}
我机器上的结果是:2000纳秒左右。使用系统纳秒级计算,但是这样的结果很不准确,因为System.nanoTime();这句执行也是需要时间的。像楼上的那样改进一下:public static void main(String[] args) {
long t0, t1;
t0 = System.nanoTime();
for(int a = 0; a < Integer.MAX_VALUE; a = a + 1);
t1 = System.nanoTime();
System.out.println((t1 - t0)/(double)Integer.MAX_VALUE + " ns");
}
这样子,我机器上的输出平均值基本上在1.7纳秒左右摆动。上面这个例子中,循环执行次数越多,所平均下来的时间就越小,在我的机器上1.7纳秒是极限值了。
加法运算是衡量cpu速度的重要标准,厂家所宣传的每秒多少次运算都是指的加法,因cpu不同而不同,不知道楼主是什么用意。