Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagecell
Path: blob/master/timing/test_scripts/timing_util.py
447 views
1
"""
2
Provide a timing utility context manager
3
"""
4
import contextlib
5
@contextlib.contextmanager
6
def timing(results=None):
7
"""
8
Time the execution of the block of code. If a results list is
9
passed in, the time is appended to the list. Also returns a list
10
of one element containing the time the execution took.
11
12
To use, do something like::
13
14
from time import sleep
15
results_list=[]
16
with timing(results_list) as t:
17
sleep(1)
18
print results_list, t
19
20
Exceptions in the code should be re-raised and the timing should
21
correctly be set regardless of the exceptions.
22
"""
23
from time import time
24
try:
25
# code in the context is executed when we yield
26
start=[time()]
27
yield start
28
except:
29
# any exceptions in the code should get propogated
30
raise
31
finally:
32
start.append(time()-start[0])
33
if results is not None:
34
results.append(start)
35
36
import urllib
37
import urllib2
38
39
try: import simplejson as json
40
except ImportError: import json
41
42
def json_request(url, data=None):
43
"""
44
Send a JSON message to the URL and return the result as a
45
dictionary.
46
47
:param data: a JSON-stringifiable object, passed in the POST
48
variable ``message``
49
:returns: a JSON-parsed dict/list/whatever from the server reply
50
"""
51
if data is not None:
52
data = urllib.urlencode(data)
53
response = urllib2.urlopen(url, data)
54
return json.loads(response.read())
55
56
57