懒惰序列评估中的经过时间

时间:2015-04-03 06:41:19

标签: time clojure lazy-evaluation lazy-sequences

鉴于此代码:

(reduce my-fun my-lazy-seq)

测量整个操作的经过时间:

(time (reduce my-fun my-lazy-seq))  ;;Elapsed time: 1000.1234 msecs

如何在完成前的各个阶段测量此循环的经过时间?例如:

Elapsed time to process next 1000 samples in my-lazy-seq: 100.1234 msecs  
Elapsed time to process next 1000 samples in my-lazy-seq: 99.1234 msecs  
Elapsed time to process next 1000 samples in my-lazy-seq: 101.1234 msecs  
...

2 个答案:

答案 0 :(得分:2)

(doseq [thousand (partition 1000 my-lazy-seq)]
  (time (reduce my-fun thousand)))

答案 1 :(得分:1)

这个怎么样:

(defn seq-counter [n coll]
  (let [t0 (System/currentTimeMillis)
        f (fn [i x]
            (let [i (inc i)]
              (if (= 0 (rem i n))
                (println i "items processed in" (- (System/currentTimeMillis) t0) "ms.")) 
              x))]
    (map-indexed f coll)))

map-indexed用于检查进度。上述函数将在每个n元素中打印计数和处理时间。

user=> (reduce + (seq-counter 10 (range 100)))
10 items processed in 0 ms.
20 items processed in 0 ms.
...
100 items processed in 1 ms.
4950

请参阅Idiomatic clojure for progress reporting?