在ARefs上的奇怪计算时间调节 [英] Strange computation times conditioning on ARefs

查看:129
本文介绍了在ARefs上的奇怪计算时间调节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数foo:

(defn foo [a b] (* a b)) ; <- 2 ms per 10K
(foo 3 8) ; <- 24

我想能够传递代理,原子或参考。

I want to be able to pass it agents, atoms, or refs as well.

(defn bar [a b] (* @a @b)) ; <- 3.5 ms per 10K

但是混合文字和代理怎么样?

But then what about mixing literals and agents?

(defn aref? [x] (isa? (class x) clojure.lang.ARef))
(defn foo [a b] (let [a (if (aref? a) @a a)
                      b (if (aref? b) @b b)]
                  (* a b))
(def x (ref 3))
(def y (ref 8))
(foo 3 8); <- 120 ms per 10K
(foo 3 y); <- 71 ms per 10K
(foo x 8); <- 73 ms per 10K
(foo x y); <- 6 ms per 10K

但这些都是一些真的时髦的运行时间。我尝试改变 foo 中的分支的顺序,为什么我的新 foo 需要20倍的时间来评价文字比超过ARefs?

But those are some really funky running times. I tried changing the order of the branching in foo, and that apparently has nothing to do with it. Why does my new foo take 20 times longer to evaluate over literals than over ARefs?

推荐答案

有效的ez121sl提到的性能差异来自使用 isa?。看看它的源代码发现它使用内置的全局层次结构(如果没有提供),并递归检查是否有任何 bases 类的子类(基类)是定义的类。

In effect as ez121sl mentioned the performance differences come from the use of isa?. Looking at its source code you'll find that it uses a built-in global-hierarchy (if none is provided) and recursively checks if any the bases (base classes) of the child class is the parent class defined.

使用 instance?(在封面后面使用Java的 instanceof?更明智。

The use of instance? (which uses Java's instanceof? behind the covers) results in times that are more sensible.

(defn aref? [x]
  (instance? clojure.lang.ARef x))

(defn foo [a b] (let [a (if (aref? a) @a a)
                      b (if (aref? b) @b b)]
                  (* a b)))
(def a (ref 3))
(def b (ref 8))
(time (dotimes [i 10000] (foo a b))) ; ~ 9ms
(time (dotimes [i 10000] (foo a 8))) ; ~ 2.7ms
(time (dotimes [i 10000] (foo 3 b))) ; ~ 2.7ms
(time (dotimes [i 10000] (foo 3 8))) ; ~ 1.7ms

这篇关于在ARefs上的奇怪计算时间调节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆