规格/有效评估时间?呈指数增长

时间:2019-01-31 13:36:55

标签: clojure clojure.spec

我正在使用clojure.spec来解析DSL。不幸的是,用于测试是否符合我的规格的计算时间似乎呈指数增长。我想了解原因以及解决方法。

规格如下:

(spec/def ::settings map?)

(spec/def ::header (spec/spec
                    (spec/cat :prefix #{:begin-example}
                              :label string?
                              :settings (spec/? ::settings))))

(def end-block [:end-example])

(spec/def ::not-end (partial not= end-block))

(spec/def ::end #{end-block})

(spec/def ::block (spec/cat
                   :header ::header
                   :data (spec/* ::not-end)
                   :suffix ::end))

(spec/def ::form (spec/alt :block ::block
                           :form any?))

(spec/def ::forms (spec/* ::form))

为了执行规范,我编写了一个小函数,可为规范生成 valid 数据,并提供一个size参数来控制数据大小:

(defn make-sample-data [size]
  (transduce
   (comp (take size)
         cat)
   conj
   []
   (repeat [:a 1 :b :c [:begin-example "a" {:indent 4}] :d :e [:end-example] 9])))

(make-sample-data 1)
;; => [:a 1 :b :c [:begin-example "a" {:indent 4}] :d :e [:end-example] 9]

(make-sample-data 2)
;; => [:a 1 :b :c [:begin-example "a" {:indent 4}] :d :e [:end-example] 9 :a 1 :b :c [:begin-example "a" {:indent 4}] :d :e [:end-example] 9]

现在我正在执行以下代码:

(dotimes [i 13]
  (assert (time (spec/valid? ::forms (make-sample-data i)))))

产生以下输出:

"Elapsed time: 0.077095 msecs"
"Elapsed time: 0.333636 msecs"
"Elapsed time: 0.864481 msecs"
"Elapsed time: 2.198994 msecs"
"Elapsed time: 4.432004 msecs"
"Elapsed time: 9.026142 msecs"
"Elapsed time: 17.709151 msecs"
"Elapsed time: 35.201316 msecs"
"Elapsed time: 73.178516 msecs"
"Elapsed time: 138.93966 msecs"
"Elapsed time: 288.349616 msecs"
"Elapsed time: 569.471181 msecs"
"Elapsed time: 1162.944497 msecs"

在我看来,对于size参数的每一步,计算时间都会加倍。

我的问题是:我如何修改规格,以使验证时间与数据大小成线性关系?

1 个答案:

答案 0 :(得分:4)

我正在猜测,性能问题来自贪婪的分支式正则表达式规范与any?谓词的组合。

any?正则表达式分支中使用s/alt :form对我来说很突出。我想规范可能会贪婪地/详尽地评估s/alt的每个分支,然后回溯,而any?会匹配所有与您的:block分支匹配的包括值。 (注意该规范符合同一无论:form any?分支之前或:block分支之后定义。)

如果您可以在顶级any?分支中使用比s/alt :form更具体的谓词,则应该看到很大的改进。我内联规范定义为简洁:

(s/def ::forms
  (s/*
    (s/alt :block
           (s/cat :header (s/spec
                            (s/cat :prefix #{:begin-example}
                                   :label string?
                                   :settings (s/? map?)))
                  :data (s/* #(not= % [:end-example]))
                  :suffix #{[:end-example]})
           :form
           (s/nonconforming ;; don't tag results
             (s/or :keyword keyword?
                   :number number?)))))

(time (s/valid? ::forms (make-sample-data 1000)))
"Elapsed time: 84.637513 msecs"
=> true

请注意,允许集合谓词(例如coll?vector?)到该:form分支会降低性能,就像any?一样。我想这是因为相同的值相匹配的s/alt

的两个分支