如何计算一次循环的循环执行时间?

时间:2013-12-06 05:20:08

标签: java collections

以下是我的代码:

public class FindTime {

HashSet<String> hashSet = new HashSet<>();

long m1() {
    hashSet.add("hai");
    hashSet.add("me");
    hashSet.add("you ");
    hashSet.add("I");
    hashSet.add("Us");
    Iterator it = hashSet.iterator();
    long startTime = System.currentTimeMillis();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
    return startTime;
}

public static void main(String[] args) {
    FindTime ft = new FindTime();
    long startTime = ft.m1();
    System.out.println("startTime" + startTime);
    long endTime = System.currentTimeMillis();
    System.out.println("End time" + endTime);
    System.out.println("d/W" + (endTime - startTime));
 }
}

我不知道那是不是正确的方法。我的要求是     “我想计算迭代HashSet所花费的时间”。

3 个答案:

答案 0 :(得分:4)

更准确地使用System.nanoTime()

public class FindTime {

HashSet<String> hashSet = new HashSet<>();

long m1() 
{
    hashSet.add("hai");
    hashSet.add("me");
    hashSet.add("you ");
    hashSet.add("I");
    hashSet.add("Us");
    Iterator it = hashSet.iterator();
    long startTime = System.nanoTime();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
    return startTime;
}

public static void main(String[] args) {
    FindTime ft = new FindTime();
    long startTime = ft.m1();

    long endTime = System.nanoTime(); //CALCULATE THE END TIME BEFORE PRINTING START TIME
           //BECAUSE PRINT OPERATION WILL ALSO TAKE TIME THAT WILL BE ADDED TO DIFFERENCE

    System.out.println("Start time in nano seconds" + startTime); //No need because you actually need difference

    System.out.println("End time in nano seconds" + endTime);
    System.out.println("Difference in Nano Seconds" + (endTime - startTime));
    //long microsecondsTime = (end - start) / 1000; //If you need in microseconds 
 }
}

答案 1 :(得分:3)

您的代码是正确的。您已经计算了在控制台中迭代和打印输出所花费的时间。打印可能比迭代花费更多时间。

您可能还退回了执行时间      return System.currentTimeMillis()- startTime;

另请参阅:Do not use System.out.println in server side code

答案 2 :(得分:1)

当你告诉你需要时间只为迭代而不是插入时,你可以像

一样使用它
long m1() {
hashSet.add("hai");
hashSet.add("me");
hashSet.add("you ");
hashSet.add("I");
hashSet.add("Us");
Iterator it = hashSet.iterator();
long startTime = System.nanoTime();

while (it.hasNext()) {
    System.out.println(it.next());
}
long endTime = System.nanoTime();
System.out.println("time taken in nano seconds" + endTime-startTime); 
return endTime-startTime;
}

原因是如果您花时间进入主要功能,那么它也会计算插入时间。 是的我同意它不会影响太多但我们知道这不是正确的事情。即使在这里我打印所以这里也会增加不完全正确的打印时间。