2017-01-02 40 views
1

我想在clojure中提取和編寫函數的執行時間,但是由於我缺乏clojure的經驗,我無法弄清楚。有沒有辦法做到這一點?如果可能,一些代碼示例將是完美的。以下是我正在調用的方法的一個示例。謝謝。在clojure中提取和寫入函數的執行時間

(dotimes [i 3] 
    (with-open [rdr (reader (str ""))] 
    (doseq [line (line-seq rdr)] 
     (display-huffman-encode line)))) 
+0

目前我有一個功能,做壓縮的字符串,我想多次執行該功能。每次執行時,我都想將執行時間寫入文件中,以便我可以進行一些分析。 – Patrick

+0

確定完成。我打電話的功能是與我的問題。 – Patrick

+0

要將代碼粘貼到問題中 - 只需粘貼它,然後選擇所有內容,然後按下'ctrl' +'K'或使用工具欄上的{}'按鈕。 –

回答

1

用於測量表達的執行時間可以使用(time exp)(簽出https://clojuredocs.org/clojure.core/time)。它打印到標準輸出,所以我想你可以在一些循環中評估你的包裝在time中的函數,然後將輸出保存到文件中。

0

方法1:使用時間宏。 (time exp)通常用於計時函數,但它會將已用時間寫入標準輸出而不是文件。您可以使用「write-out-str」來捕獲發送到標準輸出的內容並將結果寫入文件(使用「spit」)。該解決方案是(追加到文件「times.txt」):

(use 'clojure.java.io) 
(dotimes [i 3] 
    (with-open [rdr (reader "input.txt")] 
    (doseq [line (line-seq rdr)] 
     (spit "times.txt" (with-out-str (time (display-huffman-encode line))) :append true)))) 

方法2:建立自己的宏運行的功能,並返回所經過的時間。然後可以將返回的結果寫入文件。該解決方案如下所示(「工作臺」是定時例程,我添加了用於記錄和顯示Huffman編碼的單獨功能)。

(use 'clojure.java.io) 
(defn log-info 
    " Places a newline so every time is on a different line " 
    [file-name s] 
    (spit file-name (format "%s %n" (str s)) :append true)) ; %n places 
           ; platform independent newline after each time 

(defmacro bench 
    " Times the execution of your function, 
    discarding the output and returning the elapsed time in seconds 
    (you can modify this by changing the divisor from 1e9 (i.e. for milliseconds it would be 1e6." 
    ([& forms] 
    `(let [start# (System/nanoTime)] 
     [email protected] 
     (double (/ (- (System/nanoTime) start#) 1e9))))) ; Time in seconds 

(defn display-huffman-encode [x] 
    " Test example of your display function--just sleeps for 100 ms each time its called to simulate processing " 
    (Thread/sleep 100)) ; Sleeps 100 ms 

; Example code using the above elements 
; Reading and writing to the working directory with input from "input.txt" and logging output times to "times.txt" as the logged times 
(dotimes [i 3] 
    (with-open [rdr (reader "input.txt")] 
    (doseq [line (line-seq rdr)] 
    (log-info "times.txt" (bench (display-huffman-encode line)))))) 
+0

謝謝你的回答。 – Patrick