2015-09-15 63 views
0

我有以下代碼,這些代碼耗費我的時間來運行。有關如何優化它以使其更好更快的建議?如何優化java代碼 - 運行時間

   for (int tIndex = 0; tIndex < numTopics; tIndex++) { 
        double beta0 = sumTopicWordCount[tIndex] + betaSum; 
        int m0 = 0; 
        double expectWT = 1; 
        // getting the number of total words (or word w) in sentence i 
        List<String> sentenceStat = new ArrayList<String>(); 
        for(int wIndex=0 ; wIndex<sentence.size() ; wIndex++){ 
         sentenceStat.add(id2WordVocabulary.get(document.get(sIndex).get(wIndex))); 
        } 
        Set<String> unique = new HashSet<String>(sentenceStat); 
        for(String key : unique){ 
         int cnt = Collections.frequency(sentenceStat, key); 
         double betaw = topicWordCount[tIndex][word2IdVocabulary.get(key)] + beta; 
         for (int m = 0; m < cnt; m++) { 
          expectWT *= (betaw + m)/(beta0 + m0); 
          m0++; 
         } 
        } 
        multiPros[tIndex] = (docTopicCount[sIndex][tIndex] + alpha) * expectWT; 
       } 

回答

0

的問題是,你反覆掃描你的數據在一個循環:Collections.frequency一遍又一遍掃描整個列表。

除了只列出獨特的元素外,您可以一次計數它們。我假設在下面的Java 5-7;在Java 8中,它會被縮短,可能會更快。

Map<String, Integer> unique = new HashMap<String, Integer>(); 
    for(String s: sentenceStat) { 
     Integer cnt = unique.get(s); 
     if (cnt == null) { 
      unique.put(s, 1); 
     } else { 
      unique.put(s, cnt + 1); 
     } 
    } 
    for(Map.Entry<String, Integer> key : unique.entrySet()){ 
     String key = entry.getKey(); 
     int cnt = entry.getValue(); 
     double betaw = topicWordCount[tIndex][word2IdVocabulary.get(key)] + beta; 
     for (int m = 0; m < cnt; m++) { 
      expectWT *= (betaw + m)/(beta0 + m0); 
      m0++; 
     } 
    } 
+0

我得到關於HashMap的錯誤_HcorMap類型的參數數量不正確;它不能用參數參數化 _ – Sultan

+0

固定。請注意,我沒有測試代碼,它可能包含拼寫錯誤。 –

+0

它現在更快,謝謝 – Sultan