We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,860 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Need help finding time with System.currentTimeMillis()

I am finding the factorial and exponents of variables both recursively and iteratively. What I need help with is finding out how long it took each one. Where do I put the System.currentTimeMillis() part and how do I find out exactly how long it took (i.e. 55 milliseconds)?

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("What integer do you want to get the factorial of?");
    int n = scan.nextInt();
    System.out.println("The Recursive factorial of " + n + " is " + recur(n) + ".");
    System.out.println("The Iterative factorial of " + n + " is " + iter(n) + ".");
    System.out.println("What two integers do you want to get the exponent of? (a to the x)");
    int a = scan.nextInt();
    int x = scan.nextInt();
    System.out.println("The Recursive exponent of " + a + " is " + recurs(a, x) + ".");
    System.out.println("The Iterative exponent of " + a + " is " + itera(a, x) + ".");
}

public static int recur(int n){
    if(n == 0){
        return 1;
    }
    else
    return n * recur(n-1);
}

public static int iter(int n){
    if (n <= 1) {
        return 1;
    }
    int it = n;
    for (int i = n - 1; i > 1; --i) {
        it *= i;
    }
    return it;
}

public static int recurs(int a, int x){
    if (x == 0)
        return 1;
    else if (x == 1)
        return a;
    else
        return a * recurs(a, x-1);
}

public static int itera(int a, int x){
    int r = a;
    if (x == 0)
        return 1;
    else if (x == 1)
        return a;
    else
    for (int i = 1; i <= x; i ++){
        r *= a;
    }
    return r;
}
2
Contributors
2
Replies
15 Hours
Discussion Span
1 Year Ago
Last Updated
3
Views
Question
Answered
macdunk11
Newbie Poster
20 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

how do I find out exactly how long it took

Get the starting time and save it in a long variable. When done, get the current time and subtract from it the starting time to get how long it took.

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

Ok, thanks!

macdunk11
Newbie Poster
20 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 1 Year Ago by NormR1

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0671 seconds using 2.72MB