How to measure the a time-span in seconds using System.currentTimeMillis()?

前端 未结 9 578
温柔的废话
温柔的废话 2020-12-02 10:09

How to convert System.currentTimeMillis(); to seconds?

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


        
9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 10:16

    I have written the following code in my last assignment, it may help you:

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

    Just convert nano-seconds to milli-seconds.

提交回复
热议问题