Guest User

CodeReview performance string padding

a guest
Jan 5th, 2015
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 2.28 KB | None | 0 0
  1. (defun padded-string (padding n &optional from-end)
  2.   (declare (optimize speed)
  3.            (type string padding))
  4.   (with-output-to-string (s)
  5.     (loop :for i fixnum :below n
  6.        :with padding := (if from-end (reverse padding) padding)
  7.        :do (princ (char padding (mod i (length padding))) s))))
  8.  
  9. (defun pad-with-string (n str &key (from-end nil))
  10.   (declare (optimize speed)
  11.            (type string str))
  12.   (labels ((circular-list (elements)
  13.              (let ((cycle (copy-list elements)))
  14.                (nconc cycle cycle)))
  15.            (maybe-reverse (thing)
  16.              ;; cannot optimize here because `maybe-reverse'
  17.              ;; takes either string or list
  18.              (if from-end (reverse thing) thing)))
  19.     (coerce (the list (maybe-reverse
  20.                        (the list (loop repeat n
  21.                                     for c character in
  22.                                       (circular-list (coerce (the string (maybe-reverse str)) 'list))
  23.                                     collect c))))
  24.             'string)))
  25.  
  26. (defun test-padded-string ()
  27.   (declare (optimize speed))
  28.   (loop :repeat 100
  29.      :do (padded-string (make-string 1000 :initial-element #\x) 100)))
  30.  
  31. (defun test-pad-with-string ()
  32.   (declare (optimize speed))
  33.   (loop :repeat 100
  34.      :do (pad-with-string 100 (make-string 1000 :initial-element #\x))))
  35.  
  36. (defun print-test-statistics ()
  37.   (time (test-padded-string))
  38.   (gc)
  39.   (time (test-pad-with-string)))
  40.  
  41. CL-USER> (print-test-statistics)
  42. Evaluation took:
  43.   0.002 seconds of real time
  44.   0.002000 seconds of total run time (0.002000 user, 0.000000 system)
  45.   100.00% CPU
  46.   4,661,395 processor cycles
  47.   502,288 bytes consed
  48.  
  49. Evaluation took:
  50.   0.002 seconds of real time
  51.   0.002000 seconds of total run time (0.002000 user, 0.000000 system)
  52.   100.00% CPU
  53.   4,911,066 processor cycles
  54.   3,788,512 bytes consed
  55.  
  56. NIL
  57. CL-USER> (print-test-statistics)
  58. Evaluation took:
  59.   0.002 seconds of real time
  60.   0.002000 seconds of total run time (0.002000 user, 0.000000 system)
  61.   100.00% CPU
  62.   4,621,939 processor cycles
  63.   532,752 bytes consed
  64.  
  65. Evaluation took:
  66.   0.002 seconds of real time
  67.   0.002000 seconds of total run time (0.002000 user, 0.000000 system)
  68.   100.00% CPU
  69.   4,962,756 processor cycles
  70.   3,788,368 bytes consed
  71.  
  72. NIL
Advertisement
Add Comment
Please, Sign In to add comment