]> granicus.if.org Git - postgresql/commitdiff
Add likely/unlikely() branch hint macros.
authorAndres Freund <andres@anarazel.de>
Fri, 14 Oct 2016 23:05:30 +0000 (16:05 -0700)
committerAndres Freund <andres@anarazel.de>
Fri, 14 Oct 2016 23:05:30 +0000 (16:05 -0700)
These are useful for very hot code paths. Because it's easy to guess
wrongly about likelihood, and because such likelihoods change over time,
they should be used sparingly.

Past tests have shown it'd be a good idea to use them in some places,
e.g. in error checks around ereports that ERROR out, but that's work for
later.

Discussion: <20160727004333.r3e2k2y6fvk2ntup@alap3.anarazel.de>

src/include/c.h

index 4ab3f8027a56362f5c2ce3c4408f6e271edb40c1..672e21e03ea555c4fae4ca78720853a41ec24ac4 100644 (file)
@@ -939,6 +939,22 @@ typedef NameData *Name;
 #endif
 
 
+/*
+ * Hints to the compiler about the likelihood of a branch. Both likely() and
+ * unlikely() return the boolean value of the contained expression.
+ *
+ * These should only be used sparingly, in very hot code paths. It's very easy
+ * to mis-estimate likelihoods.
+ */
+#if __GNUC__ >= 3
+#define likely(x)      __builtin_expect((x) != 0, 1)
+#define unlikely(x) __builtin_expect((x) != 0, 0)
+#else
+#define likely(x)      ((x) != 0)
+#define unlikely(x) ((x) != 0)
+#endif
+
+
 /* ----------------------------------------------------------------
  *                             Section 8:      random stuff
  * ----------------------------------------------------------------