Skip to content

Instantly share code, notes, and snippets.

@bmabey
Last active December 29, 2015 18:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmabey/7714431 to your computer and use it in GitHub Desktop.
Save bmabey/7714431 to your computer and use it in GitHub Desktop.
(ns simple-sim
(require [clojure.core.async :as async]
[clojure.tools.logging :as log]
criterium.core
[com.benmabey.clj-sim :as sim]))
;; Andreas' code
(defn event [env type val]
(let [rc (async/chan)]
(async/<!!
(async/go
(async/>! (:queue @env)
{:type type :val val :rc rc :time (:now @env)})
(async/<! rc)
(async/close! rc)))))
(defn run-andreas-version []
(let [n 100000
env (atom {:now 0 :queue (async/chan)})]
;; car
(async/go
(loop []
;; (println "Driving at " (:now @env))
(event env :timeout 5)
;; (println "Parking at " (:now @env))
(event env :timeout 2)
(when (< (:now @env) n) (recur))))
(async/<!!
(async/go
(loop []
(let [e (<! (:queue @env))
nt (+ (:val e) (:now @env))]
(when (< nt n)
(swap! env assoc :now nt)
(async/go (async/>! (:rc e) true))
(recur))))))))
(comment
;; make sure you have this in your project.clj:
;; :jvm-opts ^:replace []
(criterium.core/quick-bench (run-andreas-version))
;; WARNING: Final GC required 6.817048483127273 % of runtime
;; WARNING: Final GC required 7.456380380983404 % of runtime
;; Evaluation count : 6 in 6 samples of 1 calls.
;; Execution time mean : 797.228499 ms
;; Execution time std-deviation : 19.661811 ms
;; Execution time lower quantile : 780.734999 ms ( 2.5%)
;; Execution time upper quantile : 823.866249 ms (97.5%)
;; Overhead used : 1.922486 ns
)
;; version using my (not yet released) clj-sim library
(defn run-clj-sim-version []
(let [sim-env (sim/sim-env)]
;; car
(sim/process sim-env
(loop []
;; (println "Driving at " (sim/now sim-env))
(async/<! (sim/timeout sim-env 5))
;; (println "Parking at " (sim/now sim-env))
(async/<! (sim/timeout sim-env 2))
(recur)))
(sim/run sim-env :until 100000)
(async/<!! (:stop-channel sim-env))))
(comment
(criterium.core/quick-bench (run-clj-sim-version))
;; WARNING: Final GC required 7.146535941549283 % of runtime
;; WARNING: Final GC required 9.558790452631564 % of runtime
;; Evaluation count : 6 in 6 samples of 1 calls.
;; Execution time mean : 636.968666 ms
;; Execution time std-deviation : 7.279175 ms
;; Execution time lower quantile : 627.555999 ms ( 2.5%)
;; Execution time upper quantile : 644.197749 ms (97.5%)
;; Overhead used : 1.951793 ns
)
import simpy
def clock(env, name, tick):
while True:
# print(name, env.now)
yield env.timeout(tick)
def run():
env = simpy.Environment()
env.process(clock(env, 'fast', 5))
env.process(clock(env, 'slow', 2))
env.run(until=100000)
# In [11]: %timeit run()
# 1 loops, best of 3: 311 ms per loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment