Mercurial > public > mercurial-scm > hg
comparison mercurial/util.py @ 18736:af9ddea2cb99
util: add a timed function for use during development
I often want to measure the cost of a function call before/after
an optimization, where using top level "hg --time" timing introduces
enough other noise that I can't tell if my efforts are having an
effect.
This decorator allows a developer to measure a function's cost with
finer granularity.
author | Bryan O'Sullivan <bryano@fb.com> |
---|---|
date | Thu, 28 Feb 2013 13:11:42 -0800 |
parents | 716cad930691 |
children | 9baf4330d88f |
comparison
equal
deleted
inserted
replaced
18735:716cad930691 | 18736:af9ddea2cb99 |
---|---|
1870 def isatty(fd): | 1870 def isatty(fd): |
1871 try: | 1871 try: |
1872 return fd.isatty() | 1872 return fd.isatty() |
1873 except AttributeError: | 1873 except AttributeError: |
1874 return False | 1874 return False |
1875 | |
1876 timecount = unitcountfn( | |
1877 (1, 1e3, _('%.0f s')), | |
1878 (100, 1, _('%.1f s')), | |
1879 (10, 1, _('%.2f s')), | |
1880 (1, 1, _('%.3f s')), | |
1881 (100, 0.001, _('%.1f ms')), | |
1882 (10, 0.001, _('%.2f ms')), | |
1883 (1, 0.001, _('%.3f ms')), | |
1884 (100, 0.000001, _('%.1f us')), | |
1885 (10, 0.000001, _('%.2f us')), | |
1886 (1, 0.000001, _('%.3f us')), | |
1887 (100, 0.000000001, _('%.1f ns')), | |
1888 (10, 0.000000001, _('%.2f ns')), | |
1889 (1, 0.000000001, _('%.3f ns')), | |
1890 ) | |
1891 | |
1892 _timenesting = [0] | |
1893 | |
1894 def timed(func): | |
1895 '''Report the execution time of a function call to stderr. | |
1896 | |
1897 During development, use as a decorator when you need to measure | |
1898 the cost of a function, e.g. as follows: | |
1899 | |
1900 @util.timed | |
1901 def foo(a, b, c): | |
1902 pass | |
1903 ''' | |
1904 | |
1905 def wrapper(*args, **kwargs): | |
1906 start = time.time() | |
1907 indent = 2 | |
1908 _timenesting[0] += indent | |
1909 try: | |
1910 return func(*args, **kwargs) | |
1911 finally: | |
1912 elapsed = time.time() - start | |
1913 _timenesting[0] -= indent | |
1914 sys.stderr.write('%s%s: %s\n' % | |
1915 (' ' * _timenesting[0], func.__name__, | |
1916 timecount(elapsed))) | |
1917 return wrapper |