We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
time.clock() is deprecated
Should remove and replace in timings module.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `xonsh/timings.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """Timing related functionality for the xonsh shell.
3 
4 The following time_it alias and Timer was forked from the IPython project:
5 * Copyright (c) 2008-2014, IPython Development Team
6 * Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 * Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
8 * Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
9 """
10 import os
11 import gc
12 import sys
13 import math
14 import time
15 import timeit
16 import builtins
17 import itertools
18 
19 from xonsh.lazyasd import lazyobject, lazybool
20 from xonsh.events import events
21 from xonsh.platform import ON_WINDOWS
22 
23 
24 @lazybool
25 def _HAVE_RESOURCE():
26     try:
27         import resource as r
28         have = True
29     except ImportError:
30         # There is no distinction of user/system time under windows, so we
31         # just use time.clock() for everything...
32         have = False
33     return have
34 
35 
36 @lazyobject
37 def resource():
38     import resource as r
39     return r
40 
41 
42 @lazyobject
43 def clocku():
44     if _HAVE_RESOURCE:
45         def clocku():
46             """clocku() -> floating point number
47             Return the *USER* CPU time in seconds since the start of the process.
48             This is done via a call to resource.getrusage, so it avoids the
49             wraparound problems in time.clock()."""
50             return resource.getrusage(resource.RUSAGE_SELF)[0]
51     else:
52         clocku = time.clock
53     return clocku
54 
55 
56 @lazyobject
57 def clocks():
58     if _HAVE_RESOURCE:
59         def clocks():
60             """clocks() -> floating point number
61             Return the *SYSTEM* CPU time in seconds since the start of the process.
62             This is done via a call to resource.getrusage, so it avoids the
63             wraparound problems in time.clock()."""
64             return resource.getrusage(resource.RUSAGE_SELF)[1]
65     else:
66         clocks = time.clock
67     return clocks
68 
69 
70 @lazyobject
71 def clock():
72     if _HAVE_RESOURCE:
73         def clock():
74             """clock() -> floating point number
75             Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
76             the process.  This is done via a call to resource.getrusage, so it
77             avoids the wraparound problems in time.clock()."""
78             u, s = resource.getrusage(resource.RUSAGE_SELF)[:2]
79             return u + s
80     else:
81         clock = time.clock
82     return clock
83 
84 
85 @lazyobject
86 def clock2():
87     if _HAVE_RESOURCE:
88         def clock2():
89             """clock2() -> (t_user,t_system)
90             Similar to clock(), but return a tuple of user/system times."""
91             return resource.getrusage(resource.RUSAGE_SELF)[:2]
92     else:
93         def clock2():
94             """Under windows, system CPU time can't be measured.
95             This just returns clock() and zero."""
96             return time.clock(), 0.0
97     return clock2
98 
99 
100 def format_time(timespan, precision=3):
101     """Formats the timespan in a human readable form"""
102     if timespan >= 60.0:
103         # we have more than a minute, format that in a human readable form
104         parts = [("d", 60 * 60 * 24), ("h", 60 * 60), ("min", 60), ("s", 1)]
105         time = []
106         leftover = timespan
107         for suffix, length in parts:
108             value = int(leftover / length)
109             if value > 0:
110                 leftover = leftover % length
111                 time.append('{0}{1}'.format(str(value), suffix))
112             if leftover < 1:
113                 break
114         return " ".join(time)
115     # Unfortunately the unicode 'micro' symbol can cause problems in
116     # certain terminals.
117     # See bug: https://bugs.launchpad.net/ipython/+bug/348466
118     # Try to prevent crashes by being more secure than it needs to
119     # E.g. eclipse is able to print a mu, but has no sys.stdout.encoding set.
120     units = ["s", "ms", 'us', "ns"]  # the save value
121     if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
122         try:
123             '\xb5'.encode(sys.stdout.encoding)
124             units = ["s", "ms", '\xb5s', "ns"]
125         except Exception:
126             pass
127     scaling = [1, 1e3, 1e6, 1e9]
128 
129     if timespan > 0.0:
130         order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
131     else:
132         order = 3
133     return "{1:.{0}g} {2}".format(precision, timespan * scaling[order],
134                                   units[order])
135 
136 
137 class Timer(timeit.Timer):
138     """Timer class that explicitly uses self.inner
139     which is an undocumented implementation detail of CPython,
140     not shared by PyPy.
141     """
142     # Timer.timeit copied from CPython 3.4.2
143     def timeit(self, number=timeit.default_number):
144         """Time 'number' executions of the main statement.
145         To be precise, this executes the setup statement once, and
146         then returns the time it takes to execute the main statement
147         a number of times, as a float measured in seconds.  The
148         argument is the number of times through the loop, defaulting
149         to one million.  The main statement, the setup statement and
150         the timer function to be used are passed to the constructor.
151         """
152         it = itertools.repeat(None, number)
153         gcold = gc.isenabled()
154         gc.disable()
155         try:
156             timing = self.inner(it, self.timer)
157         finally:
158             if gcold:
159                 gc.enable()
160         return timing
161 
162 
163 INNER_TEMPLATE = """
164 def inner(_it, _timer):
165     #setup
166     _t0 = _timer()
167     for _i in _it:
168         {stmt}
169     _t1 = _timer()
170     return _t1 - _t0
171 """
172 
173 
174 def timeit_alias(args, stdin=None):
175     """Runs timing study on arguments."""
176     # some real args
177     number = 0
178     quiet = False
179     repeat = 3
180     precision = 3
181     # setup
182     ctx = builtins.__xonsh_ctx__
183     timer = Timer(timer=clock)
184     stmt = ' '.join(args)
185     innerstr = INNER_TEMPLATE.format(stmt=stmt)
186     # Track compilation time so it can be reported if too long
187     # Minimum time above which compilation time will be reported
188     tc_min = 0.1
189     t0 = clock()
190     innercode = builtins.compilex(innerstr, filename='<xonsh-timeit>',
191                                   mode='exec', glbs=ctx)
192     tc = clock() - t0
193     # get inner func
194     ns = {}
195     builtins.execx(innercode, glbs=ctx, locs=ns, mode='exec')
196     timer.inner = ns['inner']
197     # Check if there is a huge difference between the best and worst timings.
198     worst_tuning = 0
199     if number == 0:
200         # determine number so that 0.2 <= total time < 2.0
201         number = 1
202         for _ in range(1, 10):
203             time_number = timer.timeit(number)
204             worst_tuning = max(worst_tuning, time_number / number)
205             if time_number >= 0.2:
206                 break
207             number *= 10
208     all_runs = timer.repeat(repeat, number)
209     best = min(all_runs) / number
210     # print some debug info
211     if not quiet:
212         worst = max(all_runs) / number
213         if worst_tuning:
214             worst = max(worst, worst_tuning)
215         # Check best timing is greater than zero to avoid a
216         # ZeroDivisionError.
217         # In cases where the slowest timing is lesser than 10 micoseconds
218         # we assume that it does not really matter if the fastest
219         # timing is 4 times faster than the slowest timing or not.
220         if worst > 4 * best and best > 0 and worst > 1e-5:
221             print(('The slowest run took {0:0.2f} times longer than the '
222                    'fastest. This could mean that an intermediate result '
223                    'is being cached.').format(worst / best))
224         print("{0} loops, best of {1}: {2} per loop"
225               .format(number, repeat, format_time(best, precision)))
226         if tc > tc_min:
227             print("Compiler time: {0:.2f} s".format(tc))
228     return
229 
230 
231 _timings = {'start': clock() if ON_WINDOWS else 0.0}
232 
233 
234 def setup_timings():
235     global _timings
236     if '--timings' in sys.argv:
237         events.doc('on_timingprobe', """
238         on_timingprobe(name: str) -> None
239 
240         Fired to insert some timings into the startuptime list
241         """)
242 
243         @events.on_timingprobe
244         def timing_on_timingprobe(name, **kw):
245             global _timings
246             _timings[name] = clock()
247 
248         @events.on_post_cmdloop
249         def timing_on_post_cmdloop(**kw):
250             global _timings
251             _timings['on_post_cmdloop'] = clock()
252 
253         @events.on_post_init
254         def timing_on_post_init(**kw):
255             global _timings
256             _timings['on_post_init'] = clock()
257 
258         @events.on_post_rc
259         def timing_on_post_rc(**kw):
260             global _timings
261             _timings['on_post_rc'] = clock()
262 
263         @events.on_postcommand
264         def timing_on_postcommand(**kw):
265             global _timings
266             _timings['on_postcommand'] = clock()
267 
268         @events.on_pre_cmdloop
269         def timing_on_pre_cmdloop(**kw):
270             global _timings
271             _timings['on_pre_cmdloop'] = clock()
272 
273         @events.on_pre_rc
274         def timing_on_pre_rc(**kw):
275             global _timings
276             _timings['on_pre_rc'] = clock()
277 
278         @events.on_precommand
279         def timing_on_precommand(**kw):
280             global _timings
281             _timings['on_precommand'] = clock()
282 
283         @events.on_ptk_create
284         def timing_on_ptk_create(**kw):
285             global _timings
286             _timings['on_ptk_create'] = clock()
287 
288         @events.on_chdir
289         def timing_on_chdir(**kw):
290             global _timings
291             _timings['on_chdir'] = clock()
292 
293         @events.on_post_prompt
294         def timing_on_post_prompt(**kw):
295             global _timings
296             _timings = {'on_post_prompt': clock()}
297 
298         @events.on_pre_prompt
299         def timing_on_pre_prompt(**kw):
300             global _timings
301             _timings['on_pre_prompt'] = clock()
302             times = list(_timings.items())
303             times = sorted(times, key=lambda x: x[1])
304             width = max(len(s) for s, _ in times) + 2
305             header_format = '|{{:<{}}}|{{:^11}}|{{:^11}}|'.format(width)
306             entry_format = '|{{:<{}}}|{{:^11.3f}}|{{:^11.3f}}|'.format(width)
307             sepline = '|{}|{}|{}|'.format('-'*width, '-'*11, '-'*11)
308             # Print result table
309             print(' Debug level: {}'.format(os.getenv('XONSH_DEBUG', 'Off')))
310             print(sepline)
311             print(header_format.format('Event name', 'Time (s)', 'Delta (s)'))
312             print(sepline)
313             prevtime = tstart = times[0][1]
314             for name, ts in times:
315                 print(entry_format.format(name, ts - tstart, ts - prevtime))
316                 prevtime = ts
317             print(sepline)
318
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/xonsh/timings.py b/xonsh/timings.py
--- a/xonsh/timings.py
+++ b/xonsh/timings.py
@@ -28,7 +28,7 @@
         have = True
     except ImportError:
         # There is no distinction of user/system time under windows, so we
-        # just use time.clock() for everything...
+        # just use time.perf_counter() for everything...
         have = False
     return have
 
@@ -44,12 +44,11 @@
     if _HAVE_RESOURCE:
         def clocku():
             """clocku() -> floating point number
-            Return the *USER* CPU time in seconds since the start of the process.
-            This is done via a call to resource.getrusage, so it avoids the
-            wraparound problems in time.clock()."""
+            Return the *USER* CPU time in seconds since the start of the
+            process."""
             return resource.getrusage(resource.RUSAGE_SELF)[0]
     else:
-        clocku = time.clock
+        clocku = time.perf_counter
     return clocku
 
 
@@ -58,12 +57,11 @@
     if _HAVE_RESOURCE:
         def clocks():
             """clocks() -> floating point number
-            Return the *SYSTEM* CPU time in seconds since the start of the process.
-            This is done via a call to resource.getrusage, so it avoids the
-            wraparound problems in time.clock()."""
+            Return the *SYSTEM* CPU time in seconds since the start of the
+            process."""
             return resource.getrusage(resource.RUSAGE_SELF)[1]
     else:
-        clocks = time.clock
+        clocks = time.perf_counter
     return clocks
 
 
@@ -72,13 +70,12 @@
     if _HAVE_RESOURCE:
         def clock():
             """clock() -> floating point number
-            Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
-            the process.  This is done via a call to resource.getrusage, so it
-            avoids the wraparound problems in time.clock()."""
+            Return the *TOTAL USER+SYSTEM* CPU time in seconds since the
+            start of the process."""
             u, s = resource.getrusage(resource.RUSAGE_SELF)[:2]
             return u + s
     else:
-        clock = time.clock
+        clock = time.perf_counter
     return clock
 
 
@@ -92,8 +89,8 @@
     else:
         def clock2():
             """Under windows, system CPU time can't be measured.
-            This just returns clock() and zero."""
-            return time.clock(), 0.0
+            This just returns perf_counter() and zero."""
+            return time.perf_counter(), 0.0
     return clock2
 
 
@@ -228,7 +225,7 @@
     return
 
 
-_timings = {'start': clock() if ON_WINDOWS else 0.0}
+_timings = {'start': clock()}
 
 
 def setup_timings():

{"golden_diff": "diff --git a/xonsh/timings.py b/xonsh/timings.py\n--- a/xonsh/timings.py\n+++ b/xonsh/timings.py\n@@ -28,7 +28,7 @@\n         have = True\n     except ImportError:\n         # There is no distinction of user/system time under windows, so we\n-        # just use time.clock() for everything...\n+        # just use time.perf_counter() for everything...\n         have = False\n     return have\n \n@@ -44,12 +44,11 @@\n     if _HAVE_RESOURCE:\n         def clocku():\n             \"\"\"clocku() -> floating point number\n-            Return the *USER* CPU time in seconds since the start of the process.\n-            This is done via a call to resource.getrusage, so it avoids the\n-            wraparound problems in time.clock().\"\"\"\n+            Return the *USER* CPU time in seconds since the start of the\n+            process.\"\"\"\n             return resource.getrusage(resource.RUSAGE_SELF)[0]\n     else:\n-        clocku = time.clock\n+        clocku = time.perf_counter\n     return clocku\n \n \n@@ -58,12 +57,11 @@\n     if _HAVE_RESOURCE:\n         def clocks():\n             \"\"\"clocks() -> floating point number\n-            Return the *SYSTEM* CPU time in seconds since the start of the process.\n-            This is done via a call to resource.getrusage, so it avoids the\n-            wraparound problems in time.clock().\"\"\"\n+            Return the *SYSTEM* CPU time in seconds since the start of the\n+            process.\"\"\"\n             return resource.getrusage(resource.RUSAGE_SELF)[1]\n     else:\n-        clocks = time.clock\n+        clocks = time.perf_counter\n     return clocks\n \n \n@@ -72,13 +70,12 @@\n     if _HAVE_RESOURCE:\n         def clock():\n             \"\"\"clock() -> floating point number\n-            Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of\n-            the process.  This is done via a call to resource.getrusage, so it\n-            avoids the wraparound problems in time.clock().\"\"\"\n+            Return the *TOTAL USER+SYSTEM* CPU time in seconds since the\n+            start of the process.\"\"\"\n             u, s = resource.getrusage(resource.RUSAGE_SELF)[:2]\n             return u + s\n     else:\n-        clock = time.clock\n+        clock = time.perf_counter\n     return clock\n \n \n@@ -92,8 +89,8 @@\n     else:\n         def clock2():\n             \"\"\"Under windows, system CPU time can't be measured.\n-            This just returns clock() and zero.\"\"\"\n-            return time.clock(), 0.0\n+            This just returns perf_counter() and zero.\"\"\"\n+            return time.perf_counter(), 0.0\n     return clock2\n \n \n@@ -228,7 +225,7 @@\n     return\n \n \n-_timings = {'start': clock() if ON_WINDOWS else 0.0}\n+_timings = {'start': clock()}\n \n \n def setup_timings():\n", "issue": "time.clock() is deprecated\nShould remove and replace in timings module.\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"Timing related functionality for the xonsh shell.\n\nThe following time_it alias and Timer was forked from the IPython project:\n* Copyright (c) 2008-2014, IPython Development Team\n* Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>\n* Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>\n* Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>\n\"\"\"\nimport os\nimport gc\nimport sys\nimport math\nimport time\nimport timeit\nimport builtins\nimport itertools\n\nfrom xonsh.lazyasd import lazyobject, lazybool\nfrom xonsh.events import events\nfrom xonsh.platform import ON_WINDOWS\n\n\n@lazybool\ndef _HAVE_RESOURCE():\n    try:\n        import resource as r\n        have = True\n    except ImportError:\n        # There is no distinction of user/system time under windows, so we\n        # just use time.clock() for everything...\n        have = False\n    return have\n\n\n@lazyobject\ndef resource():\n    import resource as r\n    return r\n\n\n@lazyobject\ndef clocku():\n    if _HAVE_RESOURCE:\n        def clocku():\n            \"\"\"clocku() -> floating point number\n            Return the *USER* CPU time in seconds since the start of the process.\n            This is done via a call to resource.getrusage, so it avoids the\n            wraparound problems in time.clock().\"\"\"\n            return resource.getrusage(resource.RUSAGE_SELF)[0]\n    else:\n        clocku = time.clock\n    return clocku\n\n\n@lazyobject\ndef clocks():\n    if _HAVE_RESOURCE:\n        def clocks():\n            \"\"\"clocks() -> floating point number\n            Return the *SYSTEM* CPU time in seconds since the start of the process.\n            This is done via a call to resource.getrusage, so it avoids the\n            wraparound problems in time.clock().\"\"\"\n            return resource.getrusage(resource.RUSAGE_SELF)[1]\n    else:\n        clocks = time.clock\n    return clocks\n\n\n@lazyobject\ndef clock():\n    if _HAVE_RESOURCE:\n        def clock():\n            \"\"\"clock() -> floating point number\n            Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of\n            the process.  This is done via a call to resource.getrusage, so it\n            avoids the wraparound problems in time.clock().\"\"\"\n            u, s = resource.getrusage(resource.RUSAGE_SELF)[:2]\n            return u + s\n    else:\n        clock = time.clock\n    return clock\n\n\n@lazyobject\ndef clock2():\n    if _HAVE_RESOURCE:\n        def clock2():\n            \"\"\"clock2() -> (t_user,t_system)\n            Similar to clock(), but return a tuple of user/system times.\"\"\"\n            return resource.getrusage(resource.RUSAGE_SELF)[:2]\n    else:\n        def clock2():\n            \"\"\"Under windows, system CPU time can't be measured.\n            This just returns clock() and zero.\"\"\"\n            return time.clock(), 0.0\n    return clock2\n\n\ndef format_time(timespan, precision=3):\n    \"\"\"Formats the timespan in a human readable form\"\"\"\n    if timespan >= 60.0:\n        # we have more than a minute, format that in a human readable form\n        parts = [(\"d\", 60 * 60 * 24), (\"h\", 60 * 60), (\"min\", 60), (\"s\", 1)]\n        time = []\n        leftover = timespan\n        for suffix, length in parts:\n            value = int(leftover / length)\n            if value > 0:\n                leftover = leftover % length\n                time.append('{0}{1}'.format(str(value), suffix))\n            if leftover < 1:\n                break\n        return \" \".join(time)\n    # Unfortunately the unicode 'micro' symbol can cause problems in\n    # certain terminals.\n    # See bug: https://bugs.launchpad.net/ipython/+bug/348466\n    # Try to prevent crashes by being more secure than it needs to\n    # E.g. eclipse is able to print a mu, but has no sys.stdout.encoding set.\n    units = [\"s\", \"ms\", 'us', \"ns\"]  # the save value\n    if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:\n        try:\n            '\\xb5'.encode(sys.stdout.encoding)\n            units = [\"s\", \"ms\", '\\xb5s', \"ns\"]\n        except Exception:\n            pass\n    scaling = [1, 1e3, 1e6, 1e9]\n\n    if timespan > 0.0:\n        order = min(-int(math.floor(math.log10(timespan)) // 3), 3)\n    else:\n        order = 3\n    return \"{1:.{0}g} {2}\".format(precision, timespan * scaling[order],\n                                  units[order])\n\n\nclass Timer(timeit.Timer):\n    \"\"\"Timer class that explicitly uses self.inner\n    which is an undocumented implementation detail of CPython,\n    not shared by PyPy.\n    \"\"\"\n    # Timer.timeit copied from CPython 3.4.2\n    def timeit(self, number=timeit.default_number):\n        \"\"\"Time 'number' executions of the main statement.\n        To be precise, this executes the setup statement once, and\n        then returns the time it takes to execute the main statement\n        a number of times, as a float measured in seconds.  The\n        argument is the number of times through the loop, defaulting\n        to one million.  The main statement, the setup statement and\n        the timer function to be used are passed to the constructor.\n        \"\"\"\n        it = itertools.repeat(None, number)\n        gcold = gc.isenabled()\n        gc.disable()\n        try:\n            timing = self.inner(it, self.timer)\n        finally:\n            if gcold:\n                gc.enable()\n        return timing\n\n\nINNER_TEMPLATE = \"\"\"\ndef inner(_it, _timer):\n    #setup\n    _t0 = _timer()\n    for _i in _it:\n        {stmt}\n    _t1 = _timer()\n    return _t1 - _t0\n\"\"\"\n\n\ndef timeit_alias(args, stdin=None):\n    \"\"\"Runs timing study on arguments.\"\"\"\n    # some real args\n    number = 0\n    quiet = False\n    repeat = 3\n    precision = 3\n    # setup\n    ctx = builtins.__xonsh_ctx__\n    timer = Timer(timer=clock)\n    stmt = ' '.join(args)\n    innerstr = INNER_TEMPLATE.format(stmt=stmt)\n    # Track compilation time so it can be reported if too long\n    # Minimum time above which compilation time will be reported\n    tc_min = 0.1\n    t0 = clock()\n    innercode = builtins.compilex(innerstr, filename='<xonsh-timeit>',\n                                  mode='exec', glbs=ctx)\n    tc = clock() - t0\n    # get inner func\n    ns = {}\n    builtins.execx(innercode, glbs=ctx, locs=ns, mode='exec')\n    timer.inner = ns['inner']\n    # Check if there is a huge difference between the best and worst timings.\n    worst_tuning = 0\n    if number == 0:\n        # determine number so that 0.2 <= total time < 2.0\n        number = 1\n        for _ in range(1, 10):\n            time_number = timer.timeit(number)\n            worst_tuning = max(worst_tuning, time_number / number)\n            if time_number >= 0.2:\n                break\n            number *= 10\n    all_runs = timer.repeat(repeat, number)\n    best = min(all_runs) / number\n    # print some debug info\n    if not quiet:\n        worst = max(all_runs) / number\n        if worst_tuning:\n            worst = max(worst, worst_tuning)\n        # Check best timing is greater than zero to avoid a\n        # ZeroDivisionError.\n        # In cases where the slowest timing is lesser than 10 micoseconds\n        # we assume that it does not really matter if the fastest\n        # timing is 4 times faster than the slowest timing or not.\n        if worst > 4 * best and best > 0 and worst > 1e-5:\n            print(('The slowest run took {0:0.2f} times longer than the '\n                   'fastest. This could mean that an intermediate result '\n                   'is being cached.').format(worst / best))\n        print(\"{0} loops, best of {1}: {2} per loop\"\n              .format(number, repeat, format_time(best, precision)))\n        if tc > tc_min:\n            print(\"Compiler time: {0:.2f} s\".format(tc))\n    return\n\n\n_timings = {'start': clock() if ON_WINDOWS else 0.0}\n\n\ndef setup_timings():\n    global _timings\n    if '--timings' in sys.argv:\n        events.doc('on_timingprobe', \"\"\"\n        on_timingprobe(name: str) -> None\n\n        Fired to insert some timings into the startuptime list\n        \"\"\")\n\n        @events.on_timingprobe\n        def timing_on_timingprobe(name, **kw):\n            global _timings\n            _timings[name] = clock()\n\n        @events.on_post_cmdloop\n        def timing_on_post_cmdloop(**kw):\n            global _timings\n            _timings['on_post_cmdloop'] = clock()\n\n        @events.on_post_init\n        def timing_on_post_init(**kw):\n            global _timings\n            _timings['on_post_init'] = clock()\n\n        @events.on_post_rc\n        def timing_on_post_rc(**kw):\n            global _timings\n            _timings['on_post_rc'] = clock()\n\n        @events.on_postcommand\n        def timing_on_postcommand(**kw):\n            global _timings\n            _timings['on_postcommand'] = clock()\n\n        @events.on_pre_cmdloop\n        def timing_on_pre_cmdloop(**kw):\n            global _timings\n            _timings['on_pre_cmdloop'] = clock()\n\n        @events.on_pre_rc\n        def timing_on_pre_rc(**kw):\n            global _timings\n            _timings['on_pre_rc'] = clock()\n\n        @events.on_precommand\n        def timing_on_precommand(**kw):\n            global _timings\n            _timings['on_precommand'] = clock()\n\n        @events.on_ptk_create\n        def timing_on_ptk_create(**kw):\n            global _timings\n            _timings['on_ptk_create'] = clock()\n\n        @events.on_chdir\n        def timing_on_chdir(**kw):\n            global _timings\n            _timings['on_chdir'] = clock()\n\n        @events.on_post_prompt\n        def timing_on_post_prompt(**kw):\n            global _timings\n            _timings = {'on_post_prompt': clock()}\n\n        @events.on_pre_prompt\n        def timing_on_pre_prompt(**kw):\n            global _timings\n            _timings['on_pre_prompt'] = clock()\n            times = list(_timings.items())\n            times = sorted(times, key=lambda x: x[1])\n            width = max(len(s) for s, _ in times) + 2\n            header_format = '|{{:<{}}}|{{:^11}}|{{:^11}}|'.format(width)\n            entry_format = '|{{:<{}}}|{{:^11.3f}}|{{:^11.3f}}|'.format(width)\n            sepline = '|{}|{}|{}|'.format('-'*width, '-'*11, '-'*11)\n            # Print result table\n            print(' Debug level: {}'.format(os.getenv('XONSH_DEBUG', 'Off')))\n            print(sepline)\n            print(header_format.format('Event name', 'Time (s)', 'Delta (s)'))\n            print(sepline)\n            prevtime = tstart = times[0][1]\n            for name, ts in times:\n                print(entry_format.format(name, ts - tstart, ts - prevtime))\n                prevtime = ts\n            print(sepline)\n", "path": "xonsh/timings.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"Timing related functionality for the xonsh shell.\n\nThe following time_it alias and Timer was forked from the IPython project:\n* Copyright (c) 2008-2014, IPython Development Team\n* Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>\n* Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>\n* Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>\n\"\"\"\nimport os\nimport gc\nimport sys\nimport math\nimport time\nimport timeit\nimport builtins\nimport itertools\n\nfrom xonsh.lazyasd import lazyobject, lazybool\nfrom xonsh.events import events\nfrom xonsh.platform import ON_WINDOWS\n\n\n@lazybool\ndef _HAVE_RESOURCE():\n    try:\n        import resource as r\n        have = True\n    except ImportError:\n        # There is no distinction of user/system time under windows, so we\n        # just use time.perf_counter() for everything...\n        have = False\n    return have\n\n\n@lazyobject\ndef resource():\n    import resource as r\n    return r\n\n\n@lazyobject\ndef clocku():\n    if _HAVE_RESOURCE:\n        def clocku():\n            \"\"\"clocku() -> floating point number\n            Return the *USER* CPU time in seconds since the start of the\n            process.\"\"\"\n            return resource.getrusage(resource.RUSAGE_SELF)[0]\n    else:\n        clocku = time.perf_counter\n    return clocku\n\n\n@lazyobject\ndef clocks():\n    if _HAVE_RESOURCE:\n        def clocks():\n            \"\"\"clocks() -> floating point number\n            Return the *SYSTEM* CPU time in seconds since the start of the\n            process.\"\"\"\n            return resource.getrusage(resource.RUSAGE_SELF)[1]\n    else:\n        clocks = time.perf_counter\n    return clocks\n\n\n@lazyobject\ndef clock():\n    if _HAVE_RESOURCE:\n        def clock():\n            \"\"\"clock() -> floating point number\n            Return the *TOTAL USER+SYSTEM* CPU time in seconds since the\n            start of the process.\"\"\"\n            u, s = resource.getrusage(resource.RUSAGE_SELF)[:2]\n            return u + s\n    else:\n        clock = time.perf_counter\n    return clock\n\n\n@lazyobject\ndef clock2():\n    if _HAVE_RESOURCE:\n        def clock2():\n            \"\"\"clock2() -> (t_user,t_system)\n            Similar to clock(), but return a tuple of user/system times.\"\"\"\n            return resource.getrusage(resource.RUSAGE_SELF)[:2]\n    else:\n        def clock2():\n            \"\"\"Under windows, system CPU time can't be measured.\n            This just returns perf_counter() and zero.\"\"\"\n            return time.perf_counter(), 0.0\n    return clock2\n\n\ndef format_time(timespan, precision=3):\n    \"\"\"Formats the timespan in a human readable form\"\"\"\n    if timespan >= 60.0:\n        # we have more than a minute, format that in a human readable form\n        parts = [(\"d\", 60 * 60 * 24), (\"h\", 60 * 60), (\"min\", 60), (\"s\", 1)]\n        time = []\n        leftover = timespan\n        for suffix, length in parts:\n            value = int(leftover / length)\n            if value > 0:\n                leftover = leftover % length\n                time.append('{0}{1}'.format(str(value), suffix))\n            if leftover < 1:\n                break\n        return \" \".join(time)\n    # Unfortunately the unicode 'micro' symbol can cause problems in\n    # certain terminals.\n    # See bug: https://bugs.launchpad.net/ipython/+bug/348466\n    # Try to prevent crashes by being more secure than it needs to\n    # E.g. eclipse is able to print a mu, but has no sys.stdout.encoding set.\n    units = [\"s\", \"ms\", 'us', \"ns\"]  # the save value\n    if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:\n        try:\n            '\\xb5'.encode(sys.stdout.encoding)\n            units = [\"s\", \"ms\", '\\xb5s', \"ns\"]\n        except Exception:\n            pass\n    scaling = [1, 1e3, 1e6, 1e9]\n\n    if timespan > 0.0:\n        order = min(-int(math.floor(math.log10(timespan)) // 3), 3)\n    else:\n        order = 3\n    return \"{1:.{0}g} {2}\".format(precision, timespan * scaling[order],\n                                  units[order])\n\n\nclass Timer(timeit.Timer):\n    \"\"\"Timer class that explicitly uses self.inner\n    which is an undocumented implementation detail of CPython,\n    not shared by PyPy.\n    \"\"\"\n    # Timer.timeit copied from CPython 3.4.2\n    def timeit(self, number=timeit.default_number):\n        \"\"\"Time 'number' executions of the main statement.\n        To be precise, this executes the setup statement once, and\n        then returns the time it takes to execute the main statement\n        a number of times, as a float measured in seconds.  The\n        argument is the number of times through the loop, defaulting\n        to one million.  The main statement, the setup statement and\n        the timer function to be used are passed to the constructor.\n        \"\"\"\n        it = itertools.repeat(None, number)\n        gcold = gc.isenabled()\n        gc.disable()\n        try:\n            timing = self.inner(it, self.timer)\n        finally:\n            if gcold:\n                gc.enable()\n        return timing\n\n\nINNER_TEMPLATE = \"\"\"\ndef inner(_it, _timer):\n    #setup\n    _t0 = _timer()\n    for _i in _it:\n        {stmt}\n    _t1 = _timer()\n    return _t1 - _t0\n\"\"\"\n\n\ndef timeit_alias(args, stdin=None):\n    \"\"\"Runs timing study on arguments.\"\"\"\n    # some real args\n    number = 0\n    quiet = False\n    repeat = 3\n    precision = 3\n    # setup\n    ctx = builtins.__xonsh_ctx__\n    timer = Timer(timer=clock)\n    stmt = ' '.join(args)\n    innerstr = INNER_TEMPLATE.format(stmt=stmt)\n    # Track compilation time so it can be reported if too long\n    # Minimum time above which compilation time will be reported\n    tc_min = 0.1\n    t0 = clock()\n    innercode = builtins.compilex(innerstr, filename='<xonsh-timeit>',\n                                  mode='exec', glbs=ctx)\n    tc = clock() - t0\n    # get inner func\n    ns = {}\n    builtins.execx(innercode, glbs=ctx, locs=ns, mode='exec')\n    timer.inner = ns['inner']\n    # Check if there is a huge difference between the best and worst timings.\n    worst_tuning = 0\n    if number == 0:\n        # determine number so that 0.2 <= total time < 2.0\n        number = 1\n        for _ in range(1, 10):\n            time_number = timer.timeit(number)\n            worst_tuning = max(worst_tuning, time_number / number)\n            if time_number >= 0.2:\n                break\n            number *= 10\n    all_runs = timer.repeat(repeat, number)\n    best = min(all_runs) / number\n    # print some debug info\n    if not quiet:\n        worst = max(all_runs) / number\n        if worst_tuning:\n            worst = max(worst, worst_tuning)\n        # Check best timing is greater than zero to avoid a\n        # ZeroDivisionError.\n        # In cases where the slowest timing is lesser than 10 micoseconds\n        # we assume that it does not really matter if the fastest\n        # timing is 4 times faster than the slowest timing or not.\n        if worst > 4 * best and best > 0 and worst > 1e-5:\n            print(('The slowest run took {0:0.2f} times longer than the '\n                   'fastest. This could mean that an intermediate result '\n                   'is being cached.').format(worst / best))\n        print(\"{0} loops, best of {1}: {2} per loop\"\n              .format(number, repeat, format_time(best, precision)))\n        if tc > tc_min:\n            print(\"Compiler time: {0:.2f} s\".format(tc))\n    return\n\n\n_timings = {'start': clock()}\n\n\ndef setup_timings():\n    global _timings\n    if '--timings' in sys.argv:\n        events.doc('on_timingprobe', \"\"\"\n        on_timingprobe(name: str) -> None\n\n        Fired to insert some timings into the startuptime list\n        \"\"\")\n\n        @events.on_timingprobe\n        def timing_on_timingprobe(name, **kw):\n            global _timings\n            _timings[name] = clock()\n\n        @events.on_post_cmdloop\n        def timing_on_post_cmdloop(**kw):\n            global _timings\n            _timings['on_post_cmdloop'] = clock()\n\n        @events.on_post_init\n        def timing_on_post_init(**kw):\n            global _timings\n            _timings['on_post_init'] = clock()\n\n        @events.on_post_rc\n        def timing_on_post_rc(**kw):\n            global _timings\n            _timings['on_post_rc'] = clock()\n\n        @events.on_postcommand\n        def timing_on_postcommand(**kw):\n            global _timings\n            _timings['on_postcommand'] = clock()\n\n        @events.on_pre_cmdloop\n        def timing_on_pre_cmdloop(**kw):\n            global _timings\n            _timings['on_pre_cmdloop'] = clock()\n\n        @events.on_pre_rc\n        def timing_on_pre_rc(**kw):\n            global _timings\n            _timings['on_pre_rc'] = clock()\n\n        @events.on_precommand\n        def timing_on_precommand(**kw):\n            global _timings\n            _timings['on_precommand'] = clock()\n\n        @events.on_ptk_create\n        def timing_on_ptk_create(**kw):\n            global _timings\n            _timings['on_ptk_create'] = clock()\n\n        @events.on_chdir\n        def timing_on_chdir(**kw):\n            global _timings\n            _timings['on_chdir'] = clock()\n\n        @events.on_post_prompt\n        def timing_on_post_prompt(**kw):\n            global _timings\n            _timings = {'on_post_prompt': clock()}\n\n        @events.on_pre_prompt\n        def timing_on_pre_prompt(**kw):\n            global _timings\n            _timings['on_pre_prompt'] = clock()\n            times = list(_timings.items())\n            times = sorted(times, key=lambda x: x[1])\n            width = max(len(s) for s, _ in times) + 2\n            header_format = '|{{:<{}}}|{{:^11}}|{{:^11}}|'.format(width)\n            entry_format = '|{{:<{}}}|{{:^11.3f}}|{{:^11.3f}}|'.format(width)\n            sepline = '|{}|{}|{}|'.format('-'*width, '-'*11, '-'*11)\n            # Print result table\n            print(' Debug level: {}'.format(os.getenv('XONSH_DEBUG', 'Off')))\n            print(sepline)\n            print(header_format.format('Event name', 'Time (s)', 'Delta (s)'))\n            print(sepline)\n            prevtime = tstart = times[0][1]\n            for name, ts in times:\n                print(entry_format.format(name, ts - tstart, ts - prevtime))\n                prevtime = ts\n            print(sepline)\n", "path": "xonsh/timings.py"}]}