SHARE
TWEET

Untitled

a guest Dec 25th, 2019 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns lab32
  2.   (:require [clojure.test :refer :all]))
  3.  
  4.  
  5. (defn pfilter
  6.   ([pred coll]
  7.    (let [n 2
  8.          cap 4]
  9.      (pfilter pred coll n cap)))
  10.   ([pred coll n cap]
  11.    (let [flat (fn flat [coll]
  12.                 (lazy-seq
  13.                   (when-let [s (seq coll)]
  14.                     (if (coll? (first s))
  15.                       (concat (flat (first s)) (flat (rest s)))
  16.                       (cons (first s) (flat (rest s)))))))
  17.          chunked (fn chunked [c]
  18.                    (lazy-seq
  19.                      (if (not-empty c)
  20.                        (cons (take cap c) (chunked (drop cap c))))))
  21.          fut (fn [c] (doall (filter pred c)))
  22.          fs (map #(future (fut %)) (chunked coll))
  23.          step (fn step [[x & xs :as vs] tail]
  24.                 (lazy-seq
  25.                   (if-let [s (seq tail)]
  26.                     (cons (deref x) (step xs (rest s)))
  27.                     (map deref vs)
  28.                     )))]
  29.      (flat (step fs (drop (dec n) fs)))
  30.      ))
  31.   )
  32.  
  33.  
  34. ;(let [coll (range 20)
  35. ;      pred (fn [x] (do
  36. ;                     (println (format "lazy%d " x))
  37. ;                     (Thread/sleep 1000)
  38. ;                     (even? x)
  39. ;                     ))
  40. ;      ]
  41. ;  (do
  42. ;    (time (doall (pfilter pred coll)))
  43. ;    )
  44. ;  )
  45.  
  46. (defmacro mtime
  47.   "Evaluates expr and prints the time it took.  Returns the value of
  48. expr."
  49.   {:added "1.0"}
  50.   [expr]
  51.   `(let [start# (. System (nanoTime))
  52.          ret# ~expr]
  53.      (/ (double (- (. System (nanoTime)) start#)) 1000000.0)))
  54.  
  55. (deftest pfilter-test
  56.   (testing "basic"
  57.     (let [coll-n 20
  58.           threads 8
  59.           coll (range coll-n)
  60.           pred even?]
  61.       (is (= (pfilter pred coll threads 1) (filter pred coll)))
  62.       (is (= (pfilter pred coll threads coll-n) (filter pred coll)))
  63.       (is (= (pfilter pred coll 1 coll-n) (filter pred coll)))
  64.       )
  65.     )
  66.   (testing "bench"
  67.     (let [coll-n 20
  68.           threads 8
  69.           sleep 1000
  70.           pred (fn [x] (do
  71.                          (Thread/sleep sleep)
  72.                          (even? x)))]
  73.       (is (< (mtime (doall (pfilter pred (range coll-n) threads 3))) (mtime (doall (filter pred (range coll-n))))))
  74.       )
  75.     ))
  76.  
  77. (run-tests 'lab32)
  78.  
  79. (shutdown-agents)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top