2017-01-02 41 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