gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:45:37 24 4
gpt4 key购买 nike

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

为此,我创建了一个代理来保存要写入的文件的路径。当我想写的时候我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。

如您所见,代理发送的代码已被注释掉。这样就可以正常执行代码了。但是,当我启用发送时,即使不写入文件,执行时间也太慢。

编辑:

我在每个线程发送给代理之前打印一个点。这些点的出现速度与没有送行时一样快。所以最后肯定有什么东西阻塞了。

我做错了什么吗?

最佳答案

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

潜在的问题是,如果您不关闭代理,则支持其线程池的线程将永远不会关闭,并阻止 JVM 退出。如果没有其他东西在运行,会有一个超时时间来关闭池,但这个时间相当长。生成操作完成后立即调用 shutdown-agents 将解决此问题。

关于multithreading - Clojure - 使用代理会大大减慢执行速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23427457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com