From 56e1e77704248ff471fc4a1b0616d1eba80837a7 Mon Sep 17 00:00:00 2001 From: David Thompson Date: Tue, 10 Jan 2017 19:28:27 -0500 Subject: math: Inline operations for performance improvements. --- chickadee/math.scm | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/chickadee/math.scm b/chickadee/math.scm index 753f70d..3bcda52 100644 --- a/chickadee/math.scm +++ b/chickadee/math.scm @@ -16,11 +16,37 @@ ;;; . (define-module (chickadee math) - #:export (clamp)) + #:export (square + clamp + min + max) + #:replace (min max)) -(define (clamp min max x) +(define-inlinable (square x) + (* x x)) + +(define-inlinable (clamp min max x) "Restrict X to the range defined by MIN and MAX. Assumes that MIN is actually less than MAX." (cond ((< x min) min) ((> x max) max) (else x))) + +;; Some macro trickery to inline calls to min/max with 2 arguments. +;; We often call min/max on floating point values, so inlining such +;; calls allows the compiler to unbox many of these operations, +;; reducing allocation. +(define-syntax min + (syntax-rules () + ((_ a b) + (if (< a b) a b)) + ((_ a b ...) + (let ((m (min b ...))) + (if (< a m) a m))))) + +(define-syntax max + (syntax-rules () + ((_ a b) (if (> a b) a b)) + ((_ a b ...) + (let ((m (max b ...))) + (if (> a m) a m))))) -- cgit v1.2.3