Path: blob/master/timing/test_scripts/simple_computation.py
447 views
1from urllib2 import urlopen2from urllib import urlencode3import json4from random import random5from time import sleep, time6import sys7from multiprocessing import Pool8import contextlib9import traceback1011from timing_util import timing, json, json_request12from time import time1314from sagecell import Session1516class Transaction(object):17def __init__(self, **kwargs):18self.custom_timers={}19self.MAXRAND=kwargs.get('maxrand', 2**30)20self.BASE_URL=kwargs.get('base_url', 'http://localhost:8080/')21self.POLL_INTERVAL=kwargs.get('poll_interval', 0.25)22self.TIMEOUT=kwargs.get('timeout', 30)2324def run(self):25"""26Ask for the sum of two random numbers and check the result27"""28computation_times=[]29response_times=[]30a=int(random()*self.MAXRAND)31b=int(random()*self.MAXRAND)32code=json.dumps('print(%d+%d)' % (a, b))33s=Session(self.BASE_URL)34request=s.prepare_execution_request(code)35sequence=03637with timing(computation_times):38with timing(response_times):39s.send_execution_request(request)40start_time = time()41done=False42while not done:43if time()-start_time>self.TIMEOUT:44raise Exception("TIMEOUT")45sleep(self.POLL_INTERVAL)46with timing(response_times):47r=s.output_poll(sequence)48if len(r)==0 or 'content' not in r:49continue50for m in r['content']:51sequence+=152if (m['msg_type']=="stream"53and m['content']['name']=="stdout"):54ans=int(m['content']['data'])55if ans!=a+b:56print("COMPUTATION NOT CORRECT")57raise ValueError("Computation not correct: %s+%s!=%s, off by %s "%(a,b,ans, ans-a-b))58else:59done=True60break6162self.custom_timers['Computation']=computation_times63self.custom_timers['Response']=response_times6465__all__=['Transaction']6667if __name__ == '__main__':68import argparse6970parser = argparse.ArgumentParser(description='Run simple additionc computation.')71parser.add_argument('--base_url', default='http://localhost:8080',72help='the base url for the sage server')73parser.add_argument('-q','--quiet', dest='quiet', action='store_true')74parser.add_argument('--timeout', dest='timeout', default=30, type=float)75args = parser.parse_args()7677trans = Transaction(base_url=args.base_url, timeout=args.timeout)78trans.run()79if not args.quiet:80print(trans.custom_timers)818283