4

Measuring clojurescript performance with KLIPSE

 3 years ago
source link: https://blog.klipse.tech/clojure/2016/03/29/profiling.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Measuring clojurescript performance with KLIPSE

Mar 29, 2016 • Yehonathan Sharvit

Let’s say that you want to profile a piece of code in clojurescript. There is a cool macro for that in clojurescript: time.

time evaluates an expression and prints the time it took and returns the value of the expression.

The interesting question is:

Where does time print the time it took?

Usually, it prints in the browser console. This is because, you have probably called (enable-console-print!) somewhere in your code.

But as a KLIPSE user, you want the time to be displayed in the evaluation rectangle instead of inside the console.

It’s simple to achieve that using with-out-str.

Let’s see it in action by comparing the running time of two naive implementations for prime number generation.

Here is a very naive implementation:

xxxxxxxxxx
(defn is-prime? [n]
  (empty? (filter #(= 0 (mod n  %)) (range 2 n))))
(defn nth-prime [n]
  (last (take n (filter #(is-prime? %) (iterate inc 2)))))
(with-out-str (time (nth-prime 50)))
the evaluation will appear here (soon)...

And now a less naive implementation:

xxxxxxxxxx
(defn is-prime-opt? [n]
  (or (= 2 n)
      (not-any? #(= 0 (mod n %)) (range 3 (inc (Math/sqrt n)) 2))))
(defn nth-prime-opt [n]
  (last (take n (filter #(is-prime-opt? %) (cons 2 (iterate (partial + 2) 3))))))
(with-out-str (time (nth-prime-opt 50)))
xxxxxxxxxx
the evaluation will appear here (soon)...
If you enjoy this kind of interactive articles would you consider a (small) donation💸 on Patreon or at least giving a star⭐ for the Klispe repo on Github?

to stay up-to-date with the coolest interactive articles around the world.

Discover more cool interactive articles about javascript, clojure[script], python, ruby, scheme, c++ and even brainfuck!

Give Klipse a Github star to express how much you appreciate Code Interactivity.

Subscribe to the Klipse newsletter:

Feel free to email me [email protected] for getting practical tips and tricks in writing your first interactive blog post.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK