如何使用 System.currentTimeMillis() 以秒为单位测量时间跨度?TimeUnit

2022-08-31 17:04:42

如何转换为秒数?System.currentTimeMillis();

long start6=System.currentTimeMillis();
System.out.println(counter.countPrimes(100000000)+" for "+start6);

控制台显示我。我看不出那是多少秒。5761455 for 1307816001290

有什么帮助吗?


答案 1

TimeUnit

使用 Java 5 及更高版本中内置的 TimeUnit 枚举

long timeMillis = System.currentTimeMillis();
long timeSeconds = TimeUnit.MILLISECONDS.toSeconds(timeMillis);

答案 2
long start = System.currentTimeMillis();
counter.countPrimes(1000000);
long end = System.currentTimeMillis();

System.out.println("Took : " + ((end - start) / 1000));

更新

更准确的解决方案是:

final long start = System.nanoTime();
counter.countPrimes(1000000);
final long end = System.nanoTime();

System.out.println("Took: " + ((end - start) / 1000000) + "ms");
System.out.println("Took: " + (end - start)/ 1000000000 + " seconds");

推荐