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