【问题标题】:How to measure the a time-span in seconds using System.currentTimeMillis()?如何使用 System.currentTimeMillis() 以秒为单位测量时间跨度?
【发布时间】:2011-06-11 18:27:57
【问题描述】:

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

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

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

有什么帮助吗?

【问题讨论】:

  • long s = System.currentTimeMilis() / 1000L
  • Try Instant 会更清楚:long s = Instant.now().getEpochSecond();

标签: java milliseconds


【解决方案1】:

TimeUnit

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

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

【讨论】:

  • 哇,以前没听说过 TimeUnit 的事。
  • 似乎对我不起作用:O 你能帮忙吗?它仍然给我与System.currentTimeMillis() 相同的结果
  • 没听说过这种方法,不错。但是当 1500 毫秒转换为 1 秒时,您会失去精度,这不是很好。
  • @PeterClause 当然,你会失去从小数秒到整秒的分辨率。你还能期待什么?
【解决方案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");

【讨论】:

  • 以纳秒为单位的时间需要除以 10^9 (1000000000) 才能显示为秒。无法编辑答案,因为我只需要插入 3 个字符而不是所需的 6 个字符。 :]
  • 抱歉,希望它是 ms 而不是 s。感谢您发现它。
  • 当需要几秒钟的结果时,为什么有人要使用nanoTime() 而不是currentTimeMillis()
  • 我,呃,没有考虑到这一点。了解nanoTime 的存在对我来说仍然很好,因为它在需要定时或记录大量大量操作的情况下会相当有用。
  • @Uooo currentTimeMillis() 是“墙上时间”,nanoTime() 是高分辨率经过时间。它们和它们的目的略有不同。 nanoTime() 不受本地时间设置、时钟校正等影响,并且保证以后调用与较早调用的差异永远不会是负数(在同一个 VM 上,在同一个电源周期中)。 currentTimeMillis() 没有这样的保证。使用currentTimeMillis() 回答“使用当前时间设置,自 1970 年 1 月 1 日以来经过了多少时间”,而不是“距离我上次调用此函数还经过了多少时间”
【解决方案3】:

像这样:

(int)(milliseconds / 1000)

【讨论】:

    【解决方案4】:

    从您的代码看来,您正在尝试测量计算花费了多长时间(而不是试图弄清楚当前时间是多少)。

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

    【讨论】:

      【解决方案5】:

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

      Instant.now().getEpochSecond();
      

      【讨论】:

        【解决方案6】:

        我在上次作业中写了以下代码,它可能对你有所帮助:

        // 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();
        }
        

        只需将纳秒转换为毫秒。

        【讨论】:

          【解决方案7】:
          TimeUnit.SECONDS.convert(start6, TimeUnit.MILLISECONDS);
          

          【讨论】:

            【解决方案8】:

            用于将毫秒转换为秒,因为 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
            

            【讨论】:

              【解决方案9】:
              // 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 );
              

              【讨论】:

              • 为了清楚起见而留下的内容非常令人困惑...也许您应该编辑您的帖子并解释一下。
              • 该代码只是将 m 除以 1000。使用对数、弧度和指数这样做是为了您的阅读乐趣。
              • System.out.println( "seconds: s" ); 打印文字's'
              猜你喜欢
              • 2019-08-29
              • 1970-01-01
              • 2010-09-26
              • 1970-01-01
              • 1970-01-01
              • 2016-12-14
              • 2017-06-28
              • 2019-01-09
              相关资源
              最近更新 更多