urn_to_hrn() is no longer lossy. urn_to_hrn() escapes '.' instead of replacing it...
[sfa.git] / sfa / util / debug.py
1 ### $Id$
2 ### $URL$
3
4 import time
5 import sys
6 import syslog
7
8 class unbuffered:
9     """
10     Write to /var/log/httpd/error_log. See
11
12     http://www.modpython.org/FAQ/faqw.py?req=edit&file=faq02.003.htp
13     """
14
15     def write(self, data):
16         sys.stderr.write(data)
17         sys.stderr.flush()
18
19 log = unbuffered()
20
21 def profile(callable):
22     """
23     Prints the runtime of the specified callable. Use as a decorator, e.g.,
24
25         @profile
26         def foo(...):
27             ...
28
29     Or, equivalently,
30
31         def foo(...):
32             ...
33         foo = profile(foo)
34
35     Or inline:
36
37         result = profile(foo)(...)
38     """
39
40     def wrapper(*args, **kwds):
41         start = time.time()
42         result = callable(*args, **kwds)
43         end = time.time()
44         args = map(str, args)
45         args += ["%s = %s" % (name, str(value)) for (name, value) in kwds.items()]
46         print >> log, "%s (%s): %f s" % (callable.__name__, ", ".join(args), end - start)
47         return result
48
49     return wrapper
50
51 if __name__ == "__main__":
52     def sleep(seconds = 1):
53         time.sleep(seconds)
54
55     sleep = profile(sleep)
56
57     sleep(1)