]> granicus.if.org Git - python/commitdiff
Issue #16674: random.getrandbits() is now 20-40% faster for small integers.
authorSerhiy Storchaka <storchaka@gmail.com>
Fri, 4 Jan 2013 10:18:35 +0000 (12:18 +0200)
committerSerhiy Storchaka <storchaka@gmail.com>
Fri, 4 Jan 2013 10:18:35 +0000 (12:18 +0200)
Misc/NEWS
Modules/_randommodule.c

index 7611c0709112f4be90031ffde3ec1e73371da2ab..310a0b28998cf1e844d72ab7d21ae8e4f4e9af2b 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -201,6 +201,8 @@ Core and Builtins
 Library
 -------
 
+- Issue #16674: random.getrandbits() is now 20-40% faster for small integers.
+
 - Issue #16009: JSON error messages now provide more information.
 
 - Issue #16828: Fix error incorrectly raised by bz2.compress(b'') and
index d8927c05b5f0f008be85cf33a154b69e59754049..a729817f3dd0b84799e1cfb23c2e553290e2e663 100644 (file)
@@ -360,6 +360,9 @@ random_getrandbits(RandomObject *self, PyObject *args)
         return NULL;
     }
 
+    if (k <= 32)  /* Fast path */
+        return PyLong_FromUnsignedLong(genrand_int32(self) >> (32 - k));
+
     bytes = ((k - 1) / 32 + 1) * 4;
     bytearray = (unsigned char *)PyMem_Malloc(bytes);
     if (bytearray == NULL) {