Skip to content

Instantly share code, notes, and snippets.

@wasamasa
Created January 23, 2016 10:05
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 wasamasa/e5f0489676e7ac769e91 to your computer and use it in GitHub Desktop.
Save wasamasa/e5f0489676e7ac769e91 to your computer and use it in GitHub Desktop.
Fun with CCL
;; taken from http://www.myrkraverk.com/blog/2014/11/the-convoluted-logic-of-rot13-in-ccl/
(define-ccl-program my-ccl-rot13
'(1
((loop
(read r0)
;; The convoluted logic of rot13 in CCL.
(if (r0 >= 110) ; n
(if (r0 <= 122) ; z
((r0 -= 13))) ;; If we are between n-z
(if (r0 >= 97) ; a
(if (r0 <= 109) ; m
((r0 += 13))) ;; If we are between a-m
(if (r0 >= 78) ; N
(if (r0 <= 90) ; Z
((r0 -= 13))) ;; If we are between N-Z
(if (r0 >= 65) ; A
(if (r0 <= 77); ; M
((r0 += 13))))))) ;; If we are between A-M
(write r0)
(repeat)))))
(defun my-ccl-rot13-string (string)
(ccl-execute-on-string 'my-ccl-rot13 (vector 0 0 0 0 0 0 0 0 nil) string))
(defmacro with-timer (&rest forms)
"Run the given FORMS, counting and displaying the elapsed time."
(declare (indent 1))
(let ((nowvar (make-symbol "now"))
(body `(progn ,@forms)))
`(let ((,nowvar (current-time)))
(prog1 ,body
(let ((elapsed (float-time (time-subtract (current-time) ,nowvar))))
(when (> elapsed 0.001)
(message "spent (%.3fs)" elapsed)))))))
(defun my-rot13-string (string)
(let ((result string)
(i 0)
(length (length string)))
(while (< i length)
(let ((char (upcase (aref result i))))
(cond
((and (>= char 78) (<= char 90))
(aset result i (- char 13)))
((and (>= char 65) (<= char 77))
(aset result i (+ char 13)))))
(setq i (1+ i)))
result))
;; CCL version
(with-timer
(dotimes (_ 1000000)
(my-ccl-rot13-string (my-ccl-rot13-string "foobar")))) ;; spent (6.440s)
(byte-compile 'my-ccl-rot13-string)
(with-timer
(dotimes (_ 1000000)
(my-ccl-rot13-string (my-ccl-rot13-string "foobar")))) ;; spent (6.139s)
;; homebrew version
(with-timer
(dotimes (_ 1000000)
(my-rot13-string (my-rot13-string "foobar")))) ;; spent (17.319s)
(byte-compile 'my-rot13-string)
(with-timer
(dotimes (_ 1000000)
(my-rot13-string (my-rot13-string "foobar")))) ;; spent (4.375s)
;; official version
(with-timer
(dotimes (_ 1000000)
(rot13-string (rot13-string "foobar")))) ;; spent (58.162s)
;; NOTE no need for a byte-compiled test since it already comes
;; byte-compiled, makes one wonder though why it's so much slower...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment