在Clojure 1.2.1中,這是您的總100,000個數據集場景的1/10中略微超過1/10秒的情況。它基本上是你的代碼(這不是真正有效的clojure語法,但我們得到了要點),但以某種方式快速運行10.000倍。
;generate 10.000 datasets of 100 maps having 10 fields each
(def scenario-data
(vec (repeatedly 10000
(fn [] (vec (repeatedly 100 (fn [] (zipmap
[:a :b :c :d :e :f :g :h :i :j]
(repeatedly (fn [] (str (- (rand-int 2000) 1000))))))))))))
;now map the datasets into the reduced sums of the parsed :b fields of each dataset
(time (doall (map (fn [dataset] (reduce (fn [acc mp] (+ acc (Integer/parseInt (:b mp)))) 0 dataset))
scenario-data)))
"Elapsed time: 120.43267 msecs"
=> (2248 -6383 7890 ...)
由於這種情況是非常內存密集型(10.000的數據集〜= 600MB,總計算使用〜4GB),我不是我家的機器上運行100.000數據集的場景。不過,我可以運行它,如果我不保存在內存中的數據集,但映射了一隻懶惰的序列,而不堅持着它的頭..
(time (doall (map (fn [dataset] (reduce (fn [acc mp] (+ acc (Integer/parseInt (:b mp)))) 0 dataset))
(repeatedly 100000
(fn [] (repeatedly 100 (fn [] (zipmap
[:a :b :c :d :e :f :g :h :i :j]
(repeatedly (fn [] (str (- (rand-int 2000) 1000))))))))))))
"Elapsed time: 30242.371308 msecs"
=> (-4975 -843 1560 ...)
這30秒計算你100.000數據集的版本,並包括生成數據所需的所有時間。使用pmap
的時間大約減半(4個核心)。
編輯:在具有足夠內存的機器上創建完全實現的100.000數據集需要135秒。運行總和代碼需要約1500毫秒。使用pmap
將其削減至約750毫秒。一個read-string
版本是〜3.5倍慢。
TL/DR:您發佈的算法可以在1秒內在100.000數據集情形下運行,並提供足夠的內存。
請發佈您的完整代碼,包括您如何閱讀數據集並將其保存在內存中,並確保這次的語法和觀察結果都準確無誤。它可能更多是因爲沒有從源頭上懶散地讀取數據集而導致的內存問題。
請給真正的clojure代碼而不是這個pseude代碼。我們可以接受。 – ivant
這是真正的clojure代碼... – redhands
爲什麼不將int存儲爲int而不是字符串?性能不僅來自算法,它是結構+算法的組合 – Ankur