gpt4 book ai didi

clojure - future 比代理商慢吗?

转载 作者:行者123 更新时间:2023-12-02 10:12:14 24 4
gpt4 key购买 nike

以下代码本质上只是让您并行执行类似 (function (range n)) 的内容。

(experiment-with-agents 10000 10 #(filter prime? %))

例如,使用 10 个代理查找 0 到 10000 之间的素数。

(experiment-with-futures 10000 10 #(filter prime? %))

与 future 相同。

现在的问题是, future 的解决方案并不会因为更多的 future 而运行得更快。示例:

; Futures
(time (experiment-with-futures 10000 1 #(filter prime? %)))
"Elapsed time: 33417.524634 msecs"

(time (experiment-with-futures 10000 10 #(filter prime? %)))
"Elapsed time: 33891.495702 msecs"

; Agents
(time (experiment-with-agents 10000 1 #(filter prime? %)))
"Elapsed time: 33048.80492 msecs"

(time (experiment-with-agents 10000 10 #(filter prime? %)))
"Elapsed time: 9211.864133 msecs"
为什么?我做错了什么吗(可能是 Clojure 新手,只是在玩弄一些东西^^)?因为我认为在这种情况下 future 实际上更受欢迎。

来源:

(defn setup-agents
[coll-size num-agents]
(let [step (/ coll-size num-agents)
parts (partition step (range coll-size))
agents (for [_ (range num-agents)] (agent []) )
vect (map #(into [] [%1 %2]) agents parts)]
(vec vect)))

(defn start-agents
[coll f]
(for [[agent part] coll] (send agent into (f part))))

(defn results
[agents]
(apply await agents)
(vec (flatten (map deref agents))))

(defn experiment-with-agents
[coll-size num-agents f]
(-> (setup-agents coll-size num-agents)
(start-agents f)
(results)))

(defn experiment-with-futures
[coll-size num-futures f]
(let [step (/ coll-size num-futures)
parts (partition step (range coll-size))
futures (for [index (range num-futures)] (future (f (nth parts index))))]
(vec (flatten (map deref futures)))))

最佳答案

您会被 forexperiment-with-futures 内部生成一个惰性序列这一事实所困扰。特别是这段代码:

(for [index (range num-futures)] (future (f (nth parts index))))

不会立即创建所有的 future ;它返回一个惰性序列,在序列的内容实现之前不会创建 future。实现惰性序列的代码为:

(vec (flatten (map deref futures)))

这里,map 返回取消引用的 future 结果的惰性序列,由 future 的惰性序列支持。由于 vec 使用 map 生成的序列的结果,因此在前一个 Future 完成之前,不会提交每个新的 Future 进行处理。

要获得并行处理,您不需要延迟创建 future。尝试包装 for 循环,在 doall 中创建 future。

您看到代理有所改进的原因是在收集代理结果之前立即调用(应用等待代理)。您的 start-agents 函数还会返回一个惰性序列,并且不会实际调度代理操作。 apply 的实现细节是它完全实现了传递给它的小序列(大约 20 个项目以下)。将 agents 传递给 apply 的副作用是,在将其移交给 await 之前,会实现序列并分派(dispatch)所有代理操作。

关于clojure - future 比代理商慢吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25874868/

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