不知道如何使用System.nanoTime()我的程序

问题描述 投票:0回答:1

我需要衡量纳秒为我的项目的时间,但我不知道如何正确地落实到我的计划。我知道我需要使用类似:

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

}

java fibonacci
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.