Muli Ben-Yehuda's journal

September 6, 2003

premature optimization is the root of all evil

Filed under: Uncategorized — Muli Ben-Yehuda @ 4:31 PM

I’m taking a short break from packing and alterntating between marvelling at some of the crap I’ve managed to accumulate and the lost treasures I’m rediscovering.

On Thursday night I came home from work and studied, goofed off on IRC, and read lkml and the fifth Potter book. Reading lkml, I saw Linus saying that mprotect is mixing up PROT_XXX and VM_XXX flags, and would someone please fix it? Jamie Lokier and me ended up each writing a patch to fix it. Jamie’s patch was cleaner, but contained this “gem”:

 +/* Optimisation macro. */ 
+#define _calc_vm_trans(x,bit1,bit2) \ 
+  ((bit1) <= (bit2) ? ((x) & (bit1)) * ((bit2) / (bit1)) \ 
+   : ((x) & (bit1)) / ((bit1) / (bit2))) 

In the likely case you’re now scratching your head, here’s my version:

 
+/* check if bit1 is on in 'in'. If it is, return bit2 
+ * this is used for transltating from one bit field domain to another, 
+ * e.g. PROT_XXX to VM_XXX + */ 
+static unsigned long trans_bit(unsigned long in, unsigned long bit1, 
+		             unsigned long bit2) 
+{ 
+        if (bit1 == bit2) 
+                return (in & bit1); 
+ 
+        return  (in & bit1) ? bit2 : 0; 
+} 

I flamed Jamie gently, asking if he really thought that shaving a couple of instructions is worth the many programmer cycles this “optimization” will cost. I guess he did, because he never replied. I also guess Linus agrees, because he commited it. Furrfu. I’ll send a patch to add a bit of documentation in a day or two, if no one will beat me to it.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: