gpt4 book ai didi

clojure - 计算 Clojure channel 中的事件发生率

转载 作者:行者123 更新时间:2023-12-01 06:03:33 24 4
gpt4 key购买 nike

我想计算事件的发生率,例如按键事件,并显示它。我也想仅在第一个事件发生后才开始速率计算。另一个要求是速率计算应在一定数量的按键事件后停止。我目前的做法是

(defn keypress-chan
"Returns a channel that receives keys"
[]
(let [out (chan) handler (fn [e] (put! out (.-key e)))]
(js/document.addEventListener "keypress" handler false)
out))

(defn tick
"Pushes to `out` 1000 ms later"
[out]
(go
(<! (timeout 1000))
(>! out 1)))

(defn get-rate
"Calculates keypress per minute rate"
[ticks pressed]
(quot (* pressed 60) ticks))

(defn complete?
[count]
(>= count 100))

(defn main-loop []
(let [key-chan (keypress-chan) ticker-chan (chan)]
(go-loop [pressed 0 ticks 0]
(let [[value ch] (alts! [key-chan ticker-chan])]
(if (= ch key-chan)
(do
;; Start timer to calculate keypress rate
(if (zero? pressed)
(tick ticker-chan))

;; Do something with `value`, i. e. the key being pressed

(when-not (complete?)
(recur (inc pressed) ticks)))

(let [speed (get-rate ticks pressed)]
(swap! app-state assoc :rate rate)
(tick ticker-chan)
(recur pressed (inc ticks))))))))

所以,这是有效的,但是 main-loop 中的代码对我来说似乎很丑。我一直在想有一个“触发器”,只有当第一个值出现在 key-chan 中时才会触发。并启动计时器。然后另一个触发器在必要时停止计时器。但我是 Clojure 的新手,不知道如何使用 async ,所以我无法创建比上面的代码更好的东西。

如何改进这个循环?
我可以将计时器移动到函数并通过 key-chan 中的第一个值启动计时器吗? ?
我以后如何停止该计时器?

最佳答案

我想出了以下解决方案。

(ns ratecalc.core
(:require [cljs.core.async :refer [chan <! go-loop]])
(:import [goog.date DateTime]))

(defn calc-rate [input-chan do-fun max-count]
(go-loop [count 0
start-time nil]
(<! input-chan)
(let [inc-count (inc count)
now (.getTime (DateTime.))
start-time* (if-not start-time now start-time)
rate-per-ms (/ inc-count (- now start-time*))]
(do-fun rate-per-ms)
(if (= count max-count)
rate-per-ms
(recur inc-count start-time*)))))
calc-rate函数计算每毫秒 channel 上的消息数。你可以传递一个函数来做一些副作用,比如打印当前的平均值。最后一个参数将其计算限制为最大消息数。以下是如何使用它的示例:
(calc-rate (keypress-chan) println 10)

关于clojure - 计算 Clojure channel 中的事件发生率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42431920/

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