[英]Why execution time is showing 0 milliseconds(java program )?
我正在編寫一個字數統計程序(非常基礎),並嘗試查找其執行時間。 奇怪的是,有時它在執行相同的輸入后顯示
0 milliseconds
在此之前它給出了15 milliseconds
。此外,有時對於相同的輸入顯示16毫秒,有時顯示15毫秒。為什么會有這種差異? 可能是什么原因呢?
這是程序:
import java.util.*;
public class WordCount{
public static void main(String [] args){
Scanner scan=new Scanner(System.in);
System.out.println("Enetr the Line of String");
String words=scan.nextLine();
long startTime = System.currentTimeMillis();
wordCount(words);
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("\n TotalTime = "+totalTime + " mills");
}//main
public static void wordCount(String words){
Integer c=0;
String wor[]=words.split(" ");
//System.out.println(""+Arrays.toString(wor));
HashMap<String,Integer> hm=new HashMap<String,Integer>();
for(String word: wor){
// c=(Integer)hm.get(word);
c=hm.get(word);
c=(c==null)?1:c+1; //no c++
hm.put(word,c);
}
Set keySet=hm.keySet();
Iterator it=keySet.iterator();
while(it.hasNext()){
String key=(String)it.next();
System.out.println(""+key+" = " + hm.get(key));
}
}//wordCount
}//class
輸出畫面:
H:\Computer Science\Java>java WordCount
Enetr the Line of String
the is an the is an a is an the
the = 3
a = 1
is = 3
an = 3
TotalTime = 15 mills
H:\Computer Science\Java>java WordCount
Enetr the Line of String
the is an the is an a is an the
the = 3
a = 1
is = 3
an = 3
TotalTime = 16 mills
H:\Computer Science\Java>java WordCount
Enetr the Line of String
the is an the is an a is an the
the = 3
a = 1
is = 3
an = 3
TotalTime = 0 mills
H:\Computer Science\Java>java WordCount
Enetr the Line of String
the is an the is an a is an the
the = 3
a = 1
is = 3
an = 3
TotalTime = 0 mills
在System.currentTimeMillis()
JavaDoc中,我們讀取了該方法:
返回當前時間(以毫秒為單位)。 請注意,雖然返回值的時間單位為毫秒, 但該值的粒度取決於基礎操作系統,並且可能更大 。 例如,許多操作系統以幾十毫秒為單位測量時間。
對於Windows,此方法的解析時間超過1毫秒(在您的情況下約為16毫秒),這是更新計時器所需的最短時間。 這意味着當您兩次調用System.currentTimeMillis()
,將獲得兩個完全相同的結果(解釋為0)或兩個結果,這兩個結果的差異取決於在操作系統上確定時間所需的時間量。
考慮使用System.nanoTime()
代替System.currentTimeMillis()
。 它產生更精確的結果。 您可以在Oracle博客中閱讀有關時間測量的更多信息, 該博客的結尾為以下段落:
如果您對測量/計算經過時間感興趣,請始終使用System.nanoTime()。 在大多數系統上,它將給出微秒級的分辨率。 但是請注意,在某些平台上執行此調用也可能需要幾微秒的時間。
您的程序的執行時間在計算上為0。對一個小句子中的單詞進行計數不會花費毫秒的時間。 由於I / O(System.out),操作系統調度延遲,系統上正在運行的其他程序或System.currentTimeInMillis()
實現的限制,您有時可能會獲得15ms或16ms的時間。 您的單詞計數程序的實際工作時間應該為0,取出I / O。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.