不确定如何在我的程序中使用System.nanoTime()

时间:2019-02-05 00:43:12

标签: java fibonacci

我需要以纳秒为单位测量项目时间,但是我不确定如何在程序中正确实现它。我知道我需要使用类似的内容:

long startTime = System.nanoTime();

...

long endTime = System.nanoTime();

long timeElapsed = endTime - startTime;

但是我不确定我必须在哪里实现它,所以我的程序可以正常工作。这是我的代码:

import java.util.*;
public class fiboSeriesRec
{

public static void main(String[] args)
{

    //Scanner allows input from user, int in this case
    Scanner sc = new Scanner(System.in);
    long n;          //declare n as a long since numbers get too large for int
    System.out.println("How many numbers 'n' do you wish to see?"); //Prompts the user to input a number
    n = sc.nextInt();

    System.out.println("The first " + n + " Fibonacci numbers are:");
    for (long i=0; i < n; i++)              //Adds each 'n' to a list as the output
    {
        System.out.println(fibonacci(i));   //Prints out the list
    }
}
//Recursive function for fibonacci sequence
public static long fibonacci(long num) {

    if (num == 0) {
        return 0;
    }
    else if(num == 1)
    {
        return 1;
    }

    return fibonacci(num-1) + fibonacci(num-2);
}

}

1 个答案:

答案 0 :(得分:0)

我假设您正在分析代码需要多长时间?

如果是这样,则在要测量的所有内容之前启动计时器,然后在要测量的内容之后进行记录,然后找出差异。只是假装您正在使用秒表为某人计时...在这里也是一样。

这意味着您可以:

import java.util.*;
public class fiboSeriesRec {

    public static void main(String[] args) {
        //Scanner allows input from user, int in this case
        Scanner sc = new Scanner(System.in);
        long n;          //declare n as a long since numbers get too large for int
        System.out.println("How many numbers 'n' do you wish to see?"); //Prompts the user to input a number
        n = sc.nextInt();

        System.out.println("The first " + n + " Fibonacci numbers are:");

        long startTime = System.nanoTime();
        for (long i=0; i < n; i++) {              //Adds each 'n' to a list as the output
            System.out.println(fibonacci(i));   //Prints out the list
        }
        long endTime = System.nanoTime();

        System.out.println("It took " + n + " iterations: " + (endTime - startTime) + " nanoseconds");
    }

    //Recursive function for fibonacci sequence
    public static long fibonacci(long num) {

        if (num == 0) {
            return 0;
        }
        else if(num == 1)
        {
            return 1;
        }

        return fibonacci(num-1) + fibonacci(num-2);
    }
}

但是请注意,此代码正在安排打印时间,这可能是相当慢的操作,而 不能很好地衡量该功能需要花费多长时间。如果要计时,则只应计时该功能,然后将差加到一个总和上,然后在最后报告该总和。

在伪代码中,这意味着:

long sum = 0;
for (int i = 0 ...) {
    long start = recordTime();
    Object result = doCalculation();
    sum += recordTime() - start;
    // Do something with result here, like print it so you don't time  printing
}
// `sum` now contains your time without interference of the loop or printing