如何使用System.currentTimeMillis()来测量时间间隔(单位为秒)?

59

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

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

控制台显示 5761455 for 1307816001290。 我无法读取它表示的秒数。

有什么帮助吗?


3
long s = System.currentTimeMilis() / 1000L - SARose
1
尝试使用Instant会更清晰: long s = Instant.now().getEpochSecond(); - free斩
9个回答

101

时间单位

使用内置于Java 5及更高版本的TimeUnit enum

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

5
哇,以前没听说过 TimeUnit 这个东西。 - chakrit
似乎对我没有起作用 :O 你能帮忙吗?它仍然给出与 System.currentTimeMillis() 相同的结果。 - NeverGiveUp161
没听说过这种方法,不错。但是当1500毫秒转换为1秒时,你会失去精度,这不太好。 - Peter Clause
1
@PeterClause 当然,从小数秒到整秒会失去分辨率。你还能期望什么呢? - Basil Bourque

80
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");

3
将以纳秒为单位的时间除以10^9(1000000000)即可显示为秒。由于我只需要插入3个字符而不是6个,因此无法编辑答案。:] - Lilienthal
抱歉,我想要的是毫秒而不是秒。感谢你发现了这个问题。 - Nico Huysamen
7
当需要以秒为单位获取结果时,为什么有人会选择使用 nanoTime() 而不是 currentTimeMillis() - Uooo
我,嗯,没有考虑到那个。但对我来说,了解nanoTime的存在仍然是很有用的,因为在需要计时或记录许多大量操作的情况下,它会更加实用。 - Lilienthal
1
@Uooo currentTimeMillis() 是用于“墙上时间”,而 nanoTime() 是高分辨率经过的时间。它们之间有一些微小的差异和不同的目的。nanoTime() 不受本地时间设置、时钟校正等影响,并且保证后一次调用与前一次调用之间的差异永远不会是负数(在同一虚拟机中,在同一电源周期内)。对于 currentTimeMillis() 没有这样的保证。使用 currentTimeMillis() 来回答“使用当前时间设置,自1970年1月1日以来经过了多长时间”,而不是“自上次调用此函数以来经过了多长时间”。 - FPGA warrior

16

就像这样:

(int)(milliseconds / 1000)

10

Java 8现在提供了获取当前Unix时间戳最简洁的方法:

Instant.now().getEpochSecond();

9

从你的代码中可以看出,你正在尝试测量计算所花费的时间(而不是尝试找出当前时间)。

在这种情况下,你需要在计算之前和之后调用currentTimeMillis,取差值,并将结果除以1000以将毫秒转换为秒。


3
我在上次的任务中编写了以下代码,它可能对你有帮助:
// A method that converts the nano-seconds to Seconds-Minutes-Hours form
private static String formatTime(long nanoSeconds)
{
    int hours, minutes, remainder, totalSecondsNoFraction;
    double totalSeconds, seconds;


    // Calculating hours, minutes and seconds
    totalSeconds = (double) nanoSeconds / 1000000000.0;
    String s = Double.toString(totalSeconds);
    String [] arr = s.split("\\.");
    totalSecondsNoFraction = Integer.parseInt(arr[0]);
    hours = totalSecondsNoFraction / 3600;
    remainder = totalSecondsNoFraction % 3600;
    minutes = remainder / 60;
    seconds = remainder % 60;
    if(arr[1].contains("E")) seconds = Double.parseDouble("." + arr[1]);
    else seconds += Double.parseDouble("." + arr[1]);


    // Formatting the string that conatins hours, minutes and seconds
    StringBuilder result = new StringBuilder(".");
    String sep = "", nextSep = " and ";
    if(seconds > 0)
    {
        result.insert(0, " seconds").insert(0, seconds);
        sep = nextSep;
        nextSep = ", ";
    }
    if(minutes > 0)
    {
        if(minutes > 1) result.insert(0, sep).insert(0, " minutes").insert(0, minutes);
        else result.insert(0, sep).insert(0, " minute").insert(0, minutes);
        sep = nextSep;
        nextSep = ", ";
    }
    if(hours > 0)
    {
        if(hours > 1) result.insert(0, sep).insert(0, " hours").insert(0, hours);
        else result.insert(0, sep).insert(0, " hour").insert(0, hours);
    }
    return result.toString();
}

只需要将纳秒转换为毫秒。


2

将毫秒转换为秒,因为1秒=10³毫秒:

//here m will be in seconds
long m = System.currentTimeMillis()/1000;

//here m will be in minutes
long m = System.currentTimeMillis()/1000/60; //this will give in mins

2
TimeUnit.SECONDS.convert(start6, TimeUnit.MILLISECONDS);

1
// Convert millis to seconds. This can be simplified a bit,
// but I left it in this form for clarity.
long m = System.currentTimeMillis(); // that's our input
int s = Math.max(
  .18 * (Math.toRadians(m)/Math.PI),
  Math.pow( Math.E, Math.log(m)-Math.log(1000) )
);
System.out.println( "seconds: "+s );

4
你为了表达清晰而留下的部分相当令人困惑......也许你应该编辑你的帖子并加以解释。 - Beau Grantham
2
那段代码只是将m除以1000。使用对数、弧度和指数来实现这一点只是为了让您阅读愉悦。 - freeideas
System.out.println( "seconds: s" ); 输出字面量的 's'。 - php_coder_3809625

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接