-2

Hi guys I made this code so far, but I need to display the execution time into miliseconds using System.currentTimeMillis(), but am not sure how!

public class Assignment4 {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        long value = System.currentTimeMillis(); 
        int n=10;
        for(int i=0;i<n;i++)
           System.out.println(i);     
    }
}
Jeff Holt
  • 2,940
  • 3
  • 22
  • 29
  • 2
    Does this answer your question? [How to print time elapsed (seconds) java](https://stackoverflow.com/questions/23207093/how-to-print-time-elapsed-seconds-java) – Jeff Holt Sep 28 '21 at 00:11
  • 1
    So, you want to display the difference between two points in time? – MadProgrammer Sep 28 '21 at 00:11
  • I essentially created a O(n) loop. I need to write down the execution time when N = 10 but the execution time right now just says 0 seconds, but I need that time in the miliseconds – Matt Brennan Sep 28 '21 at 00:15

2 Answers2

1

You need to get the timestamp at the end of the execution and subtract the initial one.

public class Assignment4 {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        long value = System.currentTimeMillis();
        int n = 10;
        for (int i = 0; i < n; i++)
            System.out.println(i);
        long totalTime =  System.currentTimeMillis()-value;
        System.out.println(totalTime);
    }
}
Andres
  • 10,561
  • 4
  • 45
  • 63
1

You can store the start and end time of the program, and print out their difference.

public static void main(String[] args) {
    long start = System.currentTimeMillis(); 
    int n=10;
    for(int i=0;i<n;i++)
       System.out.println(i);    
    long end = System.currentTimeMillis();
    System.out.println(end - start);
}