From 380bb53a423a4660f14c81448ef3f19660feac82 Mon Sep 17 00:00:00 2001
From: Michael Hanselmann <hansmi@google.com>
Date: Tue, 10 Jan 2012 15:20:05 +0100
Subject: [PATCH] utils.ResetTempfileModule: Improve performance

This function is called for after every fork (e.g. for handling an RPC
request). With the changes in this patch generating the next random
filename is about 30% faster.

Signed-off-by: Michael Hanselmann <hansmi@google.com>
Reviewed-by: Iustin Pop <iustin@google.com>
---
 lib/utils/wrapper.py | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/lib/utils/wrapper.py b/lib/utils/wrapper.py
index 256d2f1d6..55cfbf214 100644
--- a/lib/utils/wrapper.py
+++ b/lib/utils/wrapper.py
@@ -171,7 +171,7 @@ def GetClosedTempfile(*args, **kwargs):
   return path
 
 
-def ResetTempfileModule():
+def ResetTempfileModule(_time=time.time):
   """Resets the random name generator of the tempfile module.
 
   This function should be called after C{os.fork} in the child process to
@@ -182,13 +182,15 @@ def ResetTempfileModule():
 
   """
   # pylint: disable=W0212
-  if hasattr(tempfile, "_once_lock") and hasattr(tempfile, "_name_sequence"):
-    tempfile._once_lock.acquire()
+  try:
+    lock = tempfile._once_lock
+    lock.acquire()
     try:
-      # Reset random name generator
-      tempfile._name_sequence = None
+      # Re-seed random name generator
+      if tempfile._name_sequence:
+        tempfile._name_sequence.rng.seed(hash(_time()) ^ os.getpid())
     finally:
-      tempfile._once_lock.release()
-  else:
+      lock.release()
+  except AttributeError:
     logging.critical("The tempfile module misses at least one of the"
                      " '_once_lock' and '_name_sequence' attributes")
-- 
GitLab