Skip to content

Commit d64dfd9

Browse files
jtkeelingtensorflower-gardener
authored andcommitted
Use internal stack trace library in registry
This change is functionally a no-op. Instead of using the native traceback library, we use tf_stack.extract_stack() to get the frame we care about and tf_stack.convert_stack() to convert this to the same format. This reduces the number of file posix.stat calls. In my example application, we reduce the time spent in register() by a factor of 15. We also add a test to verify that we're extracting the same information. PiperOrigin-RevId: 223142289
1 parent 3f64581 commit d64dfd9

2 files changed

Lines changed: 9 additions & 6 deletions

File tree

‎tensorflow/python/framework/registry.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,9 @@
2323
from __future__ import division
2424
from __future__ import print_function
2525

26-
import traceback
27-
2826
from tensorflow.python.platform import tf_logging as logging
2927
from tensorflow.python.util import compat
28+
from tensorflow.python.util import tf_stack
3029

3130

3231
# Registry mechanism below is based on mapreduce.python.mrpython.Register.
@@ -57,15 +56,17 @@ def register(self, candidate, name=None):
5756
if name in self._registry:
5857
(filename, line_number, function_name, _) = (
5958
self._registry[name][_LOCATION_TAG])
60-
raise KeyError("Registering two %s with name '%s' !"
59+
raise KeyError("Registering two %s with name '%s'! "
6160
"(Previous registration was in %s %s:%d)" %
6261
(self._name, name, function_name, filename, line_number))
6362

6463
logging.vlog(1, "Registering %s (%s) in %s.", name, candidate, self._name)
6564
# stack trace is [this_function, Register(), user_function,...]
6665
# so the user function is #2.
67-
stack = traceback.extract_stack()
68-
self._registry[name] = {_TYPE_TAG: candidate, _LOCATION_TAG: stack[2]}
66+
stack = tf_stack.extract_stack()
67+
user_function = stack[2]
68+
location_tag = tf_stack.convert_stack([user_function])[0]
69+
self._registry[name] = {_TYPE_TAG: candidate, _LOCATION_TAG: location_tag}
6970

7071
def list(self):
7172
"""Lists registered items.

‎tensorflow/python/framework/registry_test.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,9 @@ def testRegisterFunction(self):
4545
def testDuplicate(self):
4646
myreg = registry.Registry('testbar')
4747
myreg.register(bar, 'Bar')
48-
with self.assertRaises(KeyError):
48+
with self.assertRaisesRegexp(
49+
KeyError, r'Registering two testbar with name \'Bar\'! '
50+
r'\(Previous registration was in [^ ]+ .*.py:[0-9]+\)'):
4951
myreg.register(bar, 'Bar')
5052

5153

0 commit comments

Comments
 (0)