以秒为单位打印功能的执行时间?

时间:2016-11-10 14:02:01

标签: clojure

(time(get_report))

给我“经过时间32038毫秒”。但我要秒,而不是ms。我怎样才能在Clojure中实现这一目标?

我希望它打印像“报告耗时32秒”。

立即更新我的资料:

(defmacro time
  "Evaluates expr and prints the time it took.  Returns the value of
   expr."
{:added "1.0"}
[expr]
`(let [start# (. System (nanoTime))
     ret# ~expr]
 (prn (str "Report print time: " (/ (double (- (. System (nanoTime))   start#)) 1000000000.0) " secs"))))

(time(get_report))

这是我的gather_report函数:

(defn gather_report []

(def list_of_isbns (split_isbns "src/clj_amazon/isbn_list.txt"))
(get_title_and_rank_for_all_isbns list_of_isbns)
)

2 个答案:

答案 0 :(得分:1)

这是标准定义:

(defmacro time
  "Evaluates expr and prints the time it took.  Returns the value of
 expr."
  {:added "1.0"}
  [expr]
  `(let [start# (. System (nanoTime))
         ret# ~expr]
     (prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs"))
     ret#))

注意分割表格?只需除以1000即可转换为秒。您也可以更改消息:

(defmacro time
  "Evaluates expr and prints the time it took.  Returns the value of
 expr."
  {:added "1.0"}
  [expr]
  `(let [start# (. System (nanoTime))
         ret# ~expr]
     (prn (str "Report print time: " (/ (double (- (. System (nanoTime)) start#)) 1000000000.0) " secs"))
     ret#))

查找某些内容来源的最佳方法是查找该函数的Clojure文档,然后按照“源”链接进行操作。

这就是你不在函数定义中使用def的原因:

(defn test-fn [] 
    (def some-val 20)
    (* some-val some-val)

(test-fn)

(println some-val) 
; prints 20! 

def创造了一个全球价值。你当然不希望这样!请改用let来限制范围:

(defn test-fn [] 
    (let [some-val 20]
        (* some-val some-val)) 

答案 1 :(得分:0)

您可以根据需要制作time macro的修改版本:

(defmacro sectime
  [expr]
  `(let [start# (. System (currentTimeMillis))
         ret# ~expr]
     (prn (str "Elapsed time: " (/ (double (- (. System (currentTimeMillis)) start#)) 1000.0) " secs"))
     ret#))