- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
以下代码本质上只是让您并行执行类似 (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)))))
最佳答案
您会被 for
在 experiment-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/
我正在模拟器中运行iOS应用,它要求我登录我的帐户。当我登录时有2个选择 name ----------------- Agent name (Personal Team)-- User 我该选哪个?
我是一名优秀的程序员,十分优秀!