Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagecell
Path: blob/master/timing/test_scripts/simple_computation.py
447 views
1
2
from urllib2 import urlopen
3
from urllib import urlencode
4
import json
5
from random import random
6
from time import sleep, time
7
import sys
8
from multiprocessing import Pool
9
import contextlib
10
import traceback
11
12
from timing_util import timing, json, json_request
13
from time import time
14
15
from sagecell import Session
16
17
class Transaction(object):
18
def __init__(self, **kwargs):
19
self.custom_timers={}
20
self.MAXRAND=kwargs.get('maxrand', 2**30)
21
self.BASE_URL=kwargs.get('base_url', 'http://localhost:8080/')
22
self.POLL_INTERVAL=kwargs.get('poll_interval', 0.25)
23
self.TIMEOUT=kwargs.get('timeout', 30)
24
25
def run(self):
26
"""
27
Ask for the sum of two random numbers and check the result
28
"""
29
computation_times=[]
30
response_times=[]
31
a=int(random()*self.MAXRAND)
32
b=int(random()*self.MAXRAND)
33
code=json.dumps('print(%d+%d)' % (a, b))
34
s=Session(self.BASE_URL)
35
request=s.prepare_execution_request(code)
36
sequence=0
37
38
with timing(computation_times):
39
with timing(response_times):
40
s.send_execution_request(request)
41
start_time = time()
42
done=False
43
while not done:
44
if time()-start_time>self.TIMEOUT:
45
raise Exception("TIMEOUT")
46
sleep(self.POLL_INTERVAL)
47
with timing(response_times):
48
r=s.output_poll(sequence)
49
if len(r)==0 or 'content' not in r:
50
continue
51
for m in r['content']:
52
sequence+=1
53
if (m['msg_type']=="stream"
54
and m['content']['name']=="stdout"):
55
ans=int(m['content']['data'])
56
if ans!=a+b:
57
print("COMPUTATION NOT CORRECT")
58
raise ValueError("Computation not correct: %s+%s!=%s, off by %s "%(a,b,ans, ans-a-b))
59
else:
60
done=True
61
break
62
63
self.custom_timers['Computation']=computation_times
64
self.custom_timers['Response']=response_times
65
66
__all__=['Transaction']
67
68
if __name__ == '__main__':
69
import argparse
70
71
parser = argparse.ArgumentParser(description='Run simple additionc computation.')
72
parser.add_argument('--base_url', default='http://localhost:8080',
73
help='the base url for the sage server')
74
parser.add_argument('-q','--quiet', dest='quiet', action='store_true')
75
parser.add_argument('--timeout', dest='timeout', default=30, type=float)
76
args = parser.parse_args()
77
78
trans = Transaction(base_url=args.base_url, timeout=args.timeout)
79
trans.run()
80
if not args.quiet:
81
print(trans.custom_timers)
82
83