Clojure - 使用代理会减慢执行速度

时间:2014-05-02 11:49:13

标签: multithreading clojure agents

我正在为Clojure中的程序编写基准。我有n个线程同时访问缓存。每个线程将访问缓存x次。每个请求都应记录在文件中。

为此,我创建了一个代理,用于保存要写入的文件的路径。当我想写I send-off一个写入文件并简单地返回路径的函数。这样我的文件写入就可以满足竞争条件。

当我在没有代理的情况下执行我的代码时,它在几毫秒内完成。当我使用代理时,每次我的代码运行速度非常慢时,请求每个线程发送给代理。我在谈论会议纪要。

(defn load-cache-only [usercount cache-size]
  "Test requesting from the cache only."
  ; Create the file to write the benchmark results to.
  (def sink "benchmarks/results/load-cache-only.txt")
  (let [data-agent (agent sink)
        ; Data for our backing store generated at runtime.
        store-data (into {} (map vector (map (comp keyword str)
                                             (repeat "item") 
                                             (range 1 cache-size)) 
                                        (range 1 cache-size)))
        cache      (create-full-cache cache-size store-data)]
    (barrier/run-with-barrier (fn [] (load-cache-only-work cache store-data data-agent)) usercount)))

(defn load-cache-only-work [cache store-data data-agent]
  "For use with 'load-cache-only'. Requests each item in the cache one.
   We time how long it takes for each request to be handled."
  (let [cache-size  (count store-data)
        foreachitem (fn [cache-item]
                      (let [before  (System/nanoTime)
                            result  (cache/retrieve cache cache-item)
                            after   (System/nanoTime)
                            diff_ms ((comp str float) (/ (- after before) 1000))]
                        ;(send-off data-agent (fn [filepath] 
                                           ;(file/insert-record filepath cache-size diff_ms)
                                           ;filepath))
                        ))]
    (doall (map foreachitem (keys store-data)))))

(barrier/run-with-barrier)代码只生成usercount个线程并同时启动它们(使用原子)。我传递的函数是每个线程的主体。

正文将简单地映射到名为store-data的列表,这是一个键值列表(例如,{:a 1 :b 2}。我的代码中此列表的长度现在是10。用户也是10个。

如您所见,代理发送的代码已注释掉。这使代码正常执行。但是,当我启用发送时,即使没有写入文件,执行时间也会太慢。

编辑:

我发给每个帖子,然后他发送给代理人,打印一个点。 这些点看起来和没有发送一样快。所以最后肯定会有阻塞的东西。

我做错了吗?

1 个答案:

答案 0 :(得分:5)

如果您希望JVM在合理的时间内退出,则需要在向代理发送内容时致电(shutdown-agents)

潜在的问题是,如果您不关闭代理,则支持其线程池的线程将永远不会关闭,并阻止JVM退出。如果没有其他任何东西正在运行,那么超时将关闭池,但它相当冗长。

相关问题