Example #1
0
def time_impls():
    runs = 1000
    solvers = [p2_recursive, p2_iterative_generator, p2_recursive_generator, p2_primitve]
    for solver in solvers:
        t = Timer(solver)
        assert solver() == 4613732
        print("%d runs of %s solved in %f seconds" % (runs, solver.__name__, t.timeit(number=1000)))
Example #2
0
def get_closest_region(service="ec2", repetitions=1):
    """
    Get the closest region for a particular service based on its average response time.

    :type service: str
    :param service: The service to attempt a connection to. By default, this is ``ec2``.

    :type repetitions: int
    :param repetitions: The number of measurements to take before calculating an average.
    """

    regions = [
        region.name
        for region in regioninfo.get_regions(service)
        if "gov" not in region.name and "cn" not in region.name
    ]

    latency = {}
    for region in regions:
        connection = Timer(
            "h.request('GET', '/')",
            "from http.client import HTTPSConnection; h=HTTPSConnection('%s.%s.amazonaws.com')" % (service, region),
        )
        times = connection.repeat(repetitions, 1)
        avg_latency = sum(times) / float(len(times))
        latency[region] = avg_latency
        logger.info("Average latency to Amazon %s %s is %s" % (service.upper(), region, latency[region]))

    region = min(latency, key=latency.get)

    return region
Example #3
0
 def run(self):
     """Run tests."""
     test_runs = 100
     for func in [self.all_func, self.only_id, self.few_func]:
         self.reset()
         t = Timer(func)
         print(t.timeit(number=test_runs))
Example #4
0
    def test2a_timing(self):
        """Test timing for two functions"""
        print "test2a_timing(): timings in msec/iter"
        for sz in self.sz_l[:1]:
            for spsz in self.spotsz_l:
                for pos in self.pos_l:
                    setup_str = """
from __main__ import gauss, _gauss_slow
import numpy as np
sz = (%d,%d)
spsz = %g
pos = (%d,%d)
amp = %g
noi = %g
					""" % (
                        sz + (spsz,) + pos + (self.amp, self.noi)
                    )

                    t1 = Timer(
                        """
g=_gauss_slow(sz, spsz, pos, amp, noi)
					""",
                        setup_str,
                    )
                    t2 = Timer(
                        """
a=gauss(sz, spsz, pos, amp, noi)
					""",
                        setup_str,
                    )
                    t_g1 = 1000 * min(t1.repeat(3, self.niter)) / self.niter
                    t_g2 = 1000 * min(t2.repeat(3, self.niter)) / self.niter
                    print "test2a_timing(): sz:", sz, "g1: %.3g, g2: %.3g, speedup: %.3g" % (t_g1, t_g2, t_g1 / t_g2)
    def test_console_output_and_time(self):
        " Tests the resulting console output from the framework's output. "

        regex_workers = re.compile("(Worker Thread-[\d]+ done[\n]){10}")

        saved_output = sys.stdout

        try:
            out = StringIO()
            sys.stdout = out

            control.main()

            output = out.getvalue().strip()

            # Due to random nature, separate the presence of console output
            self.assertTrue(regex_workers.match(output))
            self.assertTrue(re.search("Final length of random string: 1000", output))
            self.assertTrue(re.search("Control thread terminating", output))
            self.assertTrue(re.search("Output thread terminating", output))

            # Now that console output is nullified, log total time
            timer = Timer("t = control.main()", "from __main__ import control")

            log_info("Latest run took {} secs to complete".format(timer.timeit(number=10)))

        finally:
            sys.stdout = saved_output
Example #6
0
def time_op(op):
    from timeit import Timer
    t = Timer(op)
    result = t.timeit(number=1)
    outval = "%.5f" % (result)
    print "..done (%s)" % outval
    return outval
Example #7
0
def performance_test():
    """ Run test for the given data to test system performance. 
        (This is used for developing optimisations)
    """
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit(number=1)
Example #8
0
def time_query_using_module(module):
    # This is largely copied verbatim from the 'timeit' module
    repeat = 3
    number = 10
    verbose = True
    precision = 3
    stmt = partial(query_using_greenlets, module)
    t = Timer(stmt)
    try:
        r = t.repeat(repeat, number)
    except:
        t.print_exc()
        return 1
    best = min(r)
    if verbose:
        print("raw times:", " ".join(["%.*g" % (precision, x) for x in r]))
    print("%s: %d loops," % (module.__name__, number))
    usec = best * 1e6 / number
    if usec < 1000:
        print("best of %d: %.*g usec per loop" % (repeat, precision, usec))
    else:
        msec = usec / 1000
        if msec < 1000:
            print("best of %d: %.*g msec per loop" % (repeat, precision, msec))
        else:
            sec = msec / 1000
            print("best of %d: %.*g sec per loop" % (repeat, precision, sec))
Example #9
0
def time_stmt(stmt='pass', setup='pass', number=0, repeat=3):
    """Timer function with the same behaviour as running `python -m timeit `
    in the command line.

    :return: elapsed time in seconds or NaN if the command failed.
    :rtype: float
    """

    t = Timer(stmt, setup)

    if not number:
        # determine number so that 0.2 <= total time < 2.0
        for i in range(1, 10):
            number = 10**i

            try:
                x = t.timeit(number)
            except:
                print(t.print_exc())
                return float('NaN')

            if x >= 0.2:
                break

    try:
        r = t.repeat(repeat, number)
    except:
        print(t.print_exc())
        return float('NaN')

    best = min(r)

    return best / number
Example #10
0
def main():
    benchmarks = {}
    # Run all of the performance comparisons.
    for testname, method in tests.items():
        benchmarks[testname] = {}
        results = [None, None]
        for i, module in enumerate((re, re2)):
            # We pre-compile the pattern, because that's
            # what people do.
            current_re[0] = module.compile(method.pattern)

            results[i] = method(current_re[0], **method.data)

            # Run a test.
            t = Timer("test(current_re[0],**test.data)", setup_code % testname)
            benchmarks[testname][module.__name__] = (
                t.timeit(method.num_runs),
                method.__doc__.strip(),
                method.pattern,
                method.num_runs,
            )

        if results[0] != results[1]:
            raise ValueError("re2 output is not the same as re output: %s" % testname)

    benchmarks_to_ReST(benchmarks)
Example #11
0
 def timeit_runner(name):                                #3
     """Time one function.
     """
     timer = Timer('%s(total)' % name,
                   'from __main__ import %s\ntotal=%d'
                   % (name, total))                      #4
     return timer.timeit(number), name                   #5
def performance_experiment(use_rls):
    used_method = 'rls' if use_rls else 'svm'

    data = load_metz_data()
    split_data = leave_both_rows_and_columns_out_cv(*data)

    outer_iter = 500
    inner_iters = [1] if use_rls else [1, 10, 100]
    reg_param_range = [-7, -2, 0, 2, 7, 9] # range(-15, 16)
    reg_params = [('0', 0)] + map(lambda x: ('2^{0}'.format(x), 2**x), reg_param_range)
    for inner_iter in inner_iters:
        all_results = []
        for reg_param in reg_params:
            results = []
            params = split_data + (perfmeasure, reg_param[1], use_rls, outer_iter, inner_iter)
            timer_with_lambda = Timer(
                lambda: results.extend(single_holdout(*params)))
            lambda_perf = timer_with_lambda.timeit(number=1)
            print ('With {0} outer loops and {1} inner loops, the algorithm took in total {2} seconds. Regularization parameter {3}.'
                   .format(outer_iter, inner_iter, lambda_perf, reg_param[0]))
            print 'Results were {0}.'.format(results)
            print results
            all_results.append((results, reg_param[0]))
        plot_name = '{0}'.format(used_method) if use_rls else '{0}-iterations={1}'.format(used_method, inner_iter)
        create_plot(plot_name, all_results)
def test_mask_loss_median():
    th_mask, th_img = T.tensor4(), T.tensor4()

    cuda_out = mask_loss_median(th_mask, th_img, impl='cuda')
    cuda_mask_loss = theano.function([th_mask, th_img],
                                     [cuda_out['loss'],
                                      cuda_out['median_black'],
                                      cuda_out['loss_per_sample'],
                                      cuda_out['black_white_loss']])

    theano_mask_loss = theano.function([th_mask, th_img],
                                       mask_loss_median(th_mask, th_img,
                                                 impl='theano')['loss'])
    mask_idx = next(masks(1))
    image_ok = np.zeros_like(mask_idx)
    image_ok[mask_idx > MASK["IGNORE"]] = 1

    outs = cuda_mask_loss(mask_idx, image_ok)
    for s in outs[1:]:
        print(s.shape)
    assert (cuda_mask_loss(mask_idx, image_ok)[0] == 0).all()
    assert (theano_mask_loss(mask_idx, image_ok) == 0).all()

    t = Timer(lambda: cuda_mask_loss(mask_idx, image_ok))
    n = 10
    print("cuda implementation: {}".format(t.timeit(number=n) / n))

    t = Timer(lambda: theano_mask_loss(mask_idx, image_ok))
    print("theano implementation: {}".format(t.timeit(number=n) / n))
Example #14
0
def evaluateRunTime():
    global SDStr
    from timeit import Timer
    for SDL in SDStr:     
        print( SDL)
        t1 = Timer("Shudu(\"%s\").scanSDL()" % SDL, "from __main__ import Shudu")
        print( sum(t1.repeat(10, 1))/10)
Example #15
0
def act_as_baboon(bid, init_side):
    global avg_time
    import random
    rng = random.Random()
    rng.seed(bid)
    random = rng.random()
    
    def time_cross():
        side = init_side
        count = 0
        
        while count < num_cross:
            with turnstile:
                switches[side].lock(rope)
            with multiplex:
                sleep(random)  # simulate crossing
            switches[side].unlock(rope)
            side = 1 - side
            count += 1
    
    timer = Timer(time_cross)
    time = timer.timeit(1)
    with mutex: 
        avg_time += time
        print('Baboon {} finished in {:0.3f}s'.format(bid, time))
Example #16
0
def main():
    parser = argparse.ArgumentParser(description='Wrapper for Project Euler problems.')
    parser.add_argument('filename', metavar='FILE', help='Name of the file to run.')
    parser.add_argument('-q', dest='display_question', action='store_true', default=False, help='If present, displays the question.')
    parser.add_argument('-x', dest='no_output', action='store_true', default=False, help='If present, does not execute the question.')
    parser.add_argument('-t', dest='time_it', action='store_true', default=False, help='If prsent, measure the average execution time.')

    args = parser.parse_args()

    question = imp.load_source('question', args.filename)
    q_main = question.main

    if args.display_question:
        print q_main.__doc__

    if args.no_output:
        return

    print(q_main())

    if args.time_it:
        times = 1000 # How to set default, or value if flag present?
        print times

        from timeit import Timer
        t = Timer(lambda: q_main())
        print('{seconds} s to execute {number} times'.format(seconds=t.timeit(number=times),number=times))
Example #17
0
def main():
    global scene
    print('Reading \'{}\'...'.format(path))
    t = Timer(doImport)
    secs = t.timeit(1)
    print('> On AssimpCy Took {:0.4f} seconds.'.format(secs))
    print('\tHas {} meshes, {} textures, {} materials, {} animations'.format(scene.mNumMeshes,
                                                                             scene.mNumTextures,
                                                                             scene.mNumMaterials,
                                                                             scene.mNumAnimations))

    if scene.HasMeshes and scene.mMeshes[0].HasPositions:
        print('\tand {} vertices on mesh 0'.format(int(scene.mMeshes[0].mNumVertices)))
        v = int(scene.mMeshes[0].mNumVertices / 2)
        print('\tVertex {} = {}'.format(v, scene.mMeshes[0].mVertices[v]))
        print()
        # print(scene.mRootNode.mTransformation)

    t = Timer(doImportPy)
    secs = t.timeit(1)
    print('> On PyAssimp Took {:0.4f} seconds.'.format(secs))
    print('\tHas {} meshes, {} textures, {} materials, {} animations'.format(scene.mNumMeshes,
                                                                             scene.mNumTextures,
                                                                             scene.mNumMaterials,
                                                                             scene.mNumAnimations))

    if len(scene.meshes) and len(scene.meshes[0].vertices):
        print('\tand {} vertices on mesh 0'.format(len(scene.meshes[0].vertices)))
        v = int(len(scene.meshes[0].vertices) / 2)
        print('\tVertex {} = {}'.format(v, scene.meshes[0].vertices[v]))
        # print(scene.rootnode.transformation)
    release(scene)
def getTimeOfNumpyStatements(statement, number=1):
    t = Timer(DictionaryStatements[statement], setup="import numpy as np")
    sumAllLoopsTiming = t.timeit(number=number)
    avgTimePerLoopUsec = (sumAllLoopsTiming / number)

    # TODO: if preferred, may use repeat and get the best result with min func
    return avgTimePerLoopUsec
def no_pooling():
    """Process 10 random_wait calls sequentially"""
    def seq():
        for i in range(10):
            random_wait(i)
    t = Timer(lambda: seq())
    print('{:.5f} seconds'.format(t.timeit(number=1)))
def use_pooling():
    """Process 10 random_wait calls 5 at a time"""
    def pooled():
        with Pool(5) as pool:
            pool.map(random_wait, range(10))
    t = Timer(lambda: pooled())
    print('{:.5f} seconds'.format(t.timeit(number=1)))
Example #21
0
def run_benchmarks():
    ''' Run the benchmarks.
        An annoying screen-print will occur so that you know your
        progress, as these tests can take a while.
    '''
    times = [[0.0]*len(SIZES) for _ in range(len(GENERATORS))]

    for row,generator in enumerate(GENERATORS):
        solver = SOLVERS[row]
        print('Run #%d: %s & %s' % (row, generator, solver))
        for col,size in enumerate(SIZES):
            print(col)
            setup = """from mazelib import Maze
from mazelib.solve.%(solv)s import %(solv)s
from mazelib.generate.%(gen)s import %(gen)s
""" % {'solv': solver, 'gen': generator}
            logic = """m = Maze()
m.generator = %(gen)s(%(size)d, %(size)d)
m.solver = %(solv)s()
m.generate()
m.generate_entrances()
m.solve()
""" % {'solv': solver, 'gen': generator, 'size': size}
            t = Timer(logic, setup=setup)
            time = t.timeit(ITERATIONS[col])
            times[row][col] = time

    return times
Example #22
0
def compare_times(decorator):
    name = decorator.func_name
    setup = ("from __main__ import tre_decorator, sum_recursive, sum_iterative"
             ", _sum_recursive, %s" % name)
    t1 = Timer("with tre_decorator(%s):sum_recursive(1000)" % name, setup)
    t2 = Timer("with tre_decorator(%s):sum_iterative(1000)" % name, setup)
    return (t1.timeit(number=1000), t2.timeit(number=1000))
def exe_time(func_name, min_num, max_num):
    """Execute the function.
        
        -------------------------------------------------------
        exe_time(func_name, min_num, max_num):
        -------------------------------------------------------
        Input:
        func_name   --  the function the complexity of whic is
                        going to be measured. The function must
                        only take one integer as parameter.
        min_num     --  min possible value for the parameter.
        max_num     --  max possible value for the parameter.
        -------------------------------------------------------
        Output:
        nlist       --  a list of integers was tried
        tlist       --  a list of execution time for each 
                        integer in nlist
        -------------------------------------------------------
        """
    class wrapper(object):
        def __init__(self, n):
            self.para = n
        def __call__(self):
            return func_name(self.para)
    
    nlist = numpy.linspace(min_num, max_num, 10).astype('int64')
    tlist = numpy.empty(10)
    for i, n in enumerate(nlist):
        timer = Timer(wrapper(n))
        tlist[i] = timer.timeit(10000)
    return nlist, tlist
Example #24
0
    def run_test(self, mod, test):
        """Method runs requested test

        Args:
           mod (str): test group module
           test (str): test method

        Returns:
           list: result

        """

        self._mh.demsg('htk_on_debug_info', self._mh._trn.msg('benchmark_test_start', test), self._mh.fromhere())

        setup = 'from {0} import {1}'.format(mod, test)
        if (self._enable_gc):
            setup += '; gc.enable()'
        timer = Timer(test + '()', setup=setup)

        result = []
        for i in range(self._cycles):
            r = timer.timeit(1)
            result.append(round(r * 1000, 3))

        self._mh.demsg('htk_on_debug_info', self._mh._trn.msg('benchmark_test_finish', test), self._mh.fromhere())

        return result
Example #25
0
	def test3a_timing_calc(self):
		"""Test Zernike calculation timing and cache functioning"""

		t1 = Timer("""
a=calc_zernike(vec, rad, z_cache)
		""", """
from zern import calc_zern_basis, fit_zernike, calc_zernike
import numpy as np
rad = %d
nmodes = %d
vec = np.random.random(nmodes)
z_cache = {}
		""" % (self.rad, self.nmodes) )
		t2 = Timer("""
a=calc_zernike(vec, rad, {})
		""", """
from zern import calc_zern_basis, fit_zernike, calc_zernike
import numpy as np
rad = %d
nmodes = %d
vec = np.random.random(nmodes)
		""" % (self.rad, self.nmodes) )
		t_cache = t1.timeit(self.calc_iter)/self.calc_iter
		t_nocache = t2.timeit(self.calc_iter)/self.calc_iter
		# Caching should be at least twice as fast as no caching
		# Note that here we do not initialize the cache in the setup, it is
		# set to an empty dict which is filled on first run. This test should
		# test that this automatic filling works properly
		self.assertGreater(t_nocache/2.0, t_cache)
Example #26
0
def test_prime_pairs(times, combi_size):
    global t
    t = Timer(
        "[prime_pairs(combi,%d) for combi in combinations(xrange(100))]" % combi_size,
        "from __main__ import prime_pairs; from itertools import combinations",
    )
    print t.timeit(1)
Example #27
0
def main():
    t = Timer( 'euler14()', "from __main__ import euler14" )

    try:
        print t.timeit( 1 )
    except:
        print t.print_exc()
    def parser(self, path, articles, vocabulary):

        doc = fileinput.input(path)
        campo_aux = ""
        query = None
        for line in doc:
            i = 0
            campo = line[:2]
            if (campo == "QN"):
                if (query != None):
                    t = Timer(lambda: query.make_rank(articles, vocabulary))
                    t = t.timeit(number=1)
                    self.time = self.time + t
                    query.metrics(self)
                    print("Tempo para criar rank e ordenar", t)
                query = Query()
                line = re.sub("^" + campo, "", line)
                query.campos_dic["QN"](line)
                continue

            if (campo in Query.campos):
                campo_aux = str(campo)
                line = re.sub("^" + campo, "", line)
                query.campos_dic[campo](line)
            else:
                query.campos_dic[campo_aux](line)

        t = Timer(lambda: query.make_rank(articles, vocabulary))
        t = t.timeit(number=1)
        self.time = self.time + t
        query.metrics(self)
        print("Tempo para criar rank e ordenar", t)
 def test_time_read_line(self):
     """Test to see if continuous read of analog data is less than two secounds per call"""
     self.port.upload_code(self.pde_hex_path)
     t = Timer(lambda: self.port.read_line())
     time = t.timeit(1)
     print time
     self.assert_(time < 2)
Example #30
0
	def test3b_timing_calc(self):
		"""Test Zernike calculation performance with and without cache, print results"""

		t1 = Timer("""
a=calc_zernike(vec, rad, z_cache)
		""", """
from zern import calc_zern_basis, fit_zernike, calc_zernike
import numpy as np
rad = %d
nmodes = %d
vec = np.random.random(nmodes)
z_cache = calc_zern_basis(len(vec), rad)
		""" % (self.rad, self.nmodes) )

		t2 = Timer("""
a=calc_zernike(vec, rad, {})
		""", """
from zern import calc_zern_basis, fit_zernike, calc_zernike
import numpy as np
rad = %d
nmodes = %d
vec = np.random.random(nmodes)
		""" % (self.rad, self.nmodes) )

		t_cached = min(t1.repeat(2, self.calc_iter))/self.calc_iter
		t_nocache = min(t2.repeat(2, self.calc_iter))/self.calc_iter
		print "test3b_timing_calc(): rad=257, nmodes=25 cache: %.3g s/it no cache: %.3g s/it" % (t_cached, t_nocache)
Example #31
0
from timeit import Timer


def test1():
    l = []
    for i in range(10000):
        l = l + [i]


def test2():
    l = []
    for i in range(10000):
        l.append(i)


t1 = Timer("test1()", "from __main__ import test1")
print("", t1.timeit(number=1000), "milliseconds")

import profile
Example #32
0
def makeBezierIntermediates(node0,control0,control1,node1,epsilon):
  """Find the points, excluding node0, to be used as the line segment endpoints"""
  if(BezierWidth(node0,control0,control1,node1) <= epsilon):
    return [node1]
  else:
    splitUp = splitBezier(node0,control0,control1,node1,0.5)
    return makeBezierIntermediates(*splitUp[0]+[epsilon])+makeBezierIntermediates(*splitUp[1]+[epsilon])

def makeBezier(node0,control0,control1,node1,epsilon=1):
  """Return the vertices to be used in the polyline representation of a Bezier curve"""
  return [node0]+makeBezierIntermediates(node0,control0,control1,node1,epsilon)

if __name__ == '__main__':
  pointList = makeBezier((-80,0),(-150,40),(150,120),(80,0),0.5)
  from timeit import Timer
  t = Timer('makeBezier((-80,0),(-40,-40),(40,120),(80,0),1)','from __main__ import makeBezier')
  print pointList
  print len(pointList)
  iterations = 1000
  time = t.timeit(iterations)
  print "%d iterations took %f seconds (%f ms for each)."%(iterations,time,1000.0*time/iterations)
  points = []
  for point in pointList:
    points.append(point[0])
    points.append(-point[1])
  from Tkinter import *
  root = Tk()
  canv = Canvas(root,scrollregion=(-100,-100,100,100))
  canv.pack()
  canv.create_line(points)
  for point in pointList:
def main():
    print("Sizeof DXF string: %d" % len(dxfwrite.dxfstr(drawing)))
    t = Timer("profile_dxfstr()", setup_dxfstr)
    print_result(t.timeit(COUNT), 'using the dxfstr()')
    t = Timer("profile_save_to_fileobj()", setup_write_dxf)
    print_result(t.timeit(COUNT), 'using the save_to_fileobj()')
Example #34
0
env.reset()

# np.random.seed(0)
# env.seed(0)

ACTIVATION = 'tanh'
KERNEL_INIT = 'he_normal'
NUM_ACTIONS = env.action_space.n
NUM_HIDDEN_UNITS = 40
OBS_SPACE = env.observation_space.shape[0]
FILE_WEIGHTS = os.path.join(
    tboard_drive, ENV_NAME + COMMENT + KERNEL_INIT + '_weights' + ACTIVATION +
    str(NUM_HIDDEN_UNITS) + '.h5')
TENSORBOARD_LOG = os.path.join(
    tboard_drive, ENV_NAME + COMMENT + KERNEL_INIT + str(NUM_HIDDEN_UNITS) +
    ACTIVATION + '_units_' + str(Timer()))

RENDER = False
RESUME = False


class Model(tf.keras.Model):
    def __init__(self):
        super(Model, self).__init__(self)
        self.num_actions = NUM_ACTIONS
        self.hidden0 = tf.keras.layers.Dense(units=NUM_HIDDEN_UNITS,
                                             activation='relu',
                                             kernel_initializer=KERNEL_INIT)
        self.hidden1 = tf.keras.layers.Dense(units=NUM_HIDDEN_UNITS,
                                             activation='relu',
                                             kernel_initializer=KERNEL_INIT)
Example #35
0
def main():
    mylist = test_linkedlist_add()
    listPython = test_pythonlist_add()
    #test create and add functions for linked list
    t = timeit.timeit(test_linkedlist_add, number=1)
    print("Link list time to create and add is ", t)

    #test create and add functions for python list
    t2 = timeit.timeit(test_pythonlist_add, number=1)
    print("Python list time to create and add is ", t2)

    #check which list was faster
    if t2 > t:
        print("The Python list was faster to create a list")
    elif t2 == t:
        print("Both lists took the same amount of time")
    else:
        print("The Linked list was faster to create a list")

    #test search function for linked list
    t3 = Timer(lambda: test_linkedlist_search(mylist))
    t3 = t3.timeit(number=1)
    print("Link list time to search for two variables is  ", t3)

    #test search function for python list
    t4 = Timer(lambda: test_pythonlist_search(listPython))
    t4 = t4.timeit(number=1)
    print("Python list time to search for two variables is  ", t4)

    #check which list was faster
    if t4 > t3:
        print("The Python list was faster to search a list")
    elif t4 == t3:
        print("Both lists took the same amount of time")
    else:
        print("The Linked list was faster to search a list")

    #test size function for linked list
    t5 = Timer(lambda: test_linkedlist_size(mylist))
    t5 = t5.timeit(number=1)
    print("Link list time to check list size is  ", t5)

    #test size function for python list
    t6 = Timer(lambda: test_pythonlist_size(listPython))
    t6 = t6.timeit(number=1)
    print("Python list time to check list size is  ", t6)

    #check which list was faster
    if t6 > t5:
        print("The Python list was faster to determine the size of the list")
    elif t6 == t5:
        print("Both lists took the same amount of time")
    else:
        print("The Linked list was faster to determine the size of the list")
Example #36
0
#coding:utf-8
from timeit import Timer
from functools import lru_cache
import sys
sys.setrecursionlimit(3000)
import numpy as np
np.set_printoptions(suppress=True)


#使用functools装饰器
@lru_cache(maxsize=None)
def fib_cache(n):
    if n <= 2:
        return 1
    else:
        return fib_cache(n-1)+fib_cache(n-2)

if __name__ == "__main__":
    t1 = Timer("fib_cache(20)","from __main__ import fib_cache")
    print("fib_cache(20)",t1.timeit(number=1000),"seconds")

#计算结果
#fib_cache(100) 0.0001750409999999869 seconds
#fib_cache(50) 9.951099999999657e-05 seconds
Example #37
0
# coding: utf-8
"""
建议9:数据交换值的时候不推荐使用中间变量

对于表达式 x, y = y, x 其在内存中执行顺序如下:
1,先计算右边的表达式y,x,因此先在内存中创建元组(y, x)其标示符和值分别是y, x和其分别的值。
其中y和x是在初始化时就已经存在于内存中的对象。
2,计算表达式左边的值并进行赋值,元组被依次分配给左边的标示符,通过解包,不多解释。
"""
from timeit import Timer
num = 10**7
print(Timer('temp = x;x = y;y = temp', 'x = 2;y = 3').timeit(num))
print(Timer('x, y = y, x', 'x = 2;y = 3').timeit(num))

# 补充1:
# 不用引入Timer类,直接用timeit函数,就可以了,它会创建一个Timer,再执行类方法timeit
from timeit import timeit  # noqa
print(timeit('x, y = y, x', 'x = 2;y = 3', number=num))

# 补充2:
# 在ipython中,timeit是个魔术函数,它是ipython的内置命令,与timeit模块的timeit函数有着相似的功能,区别是timeit支持命令行形式
# Usage, in line mode:
#   %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
# or in cell mode:
#   %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
#   code
#   code...
Example #38
0
            result.append(rightList.pop(0))
    result += leftList
    result += rightList
    return result


# a = list(range(10,-1,-1))
# print(a)

# print(merge_Sort(a))
k = 1000
xVals = []
yVals = []
y1Vals = []
a0 = list(range(500, -1, -1))
t0 = Timer("merge_Sort(" + str(a0) + "),", "from __main__ import merge_Sort")
prev = min(t0.repeat(5, 5))  #t0.timeit(number=1)
for i in range(11):
    a = list(range(k, -1, -1))
    t1 = Timer("merge_Sort(" + str(a) + "),",
               "from __main__ import merge_Sort")
    time = min(t1.repeat(5, 5))
    ratio = time / prev
    xVals.append(k)
    yVals.append(prev)
    y1Vals.append(numpy.log2(ratio))
    print('array size:  ' + str(k) + '  time:  ' + str(round(prev, 3)) +
          "  s  " + "  ratio:  " + str(round(ratio, 3)) + "  coefficient:  " +
          str(round(y1Vals[i], 3)))
    prev = time
    k *= 2
Example #39
0
        print_float_array('actual means', test.x0)
        test_means = zeros(test.nstates)
        test_means[msmle.mask_nonzero] += test.x_jn.mean(axis=1)
        print_float_array('unweighted means', test_means)
        print_float_array('uwham means', xbar1)
        print_float_array('act. err', abs(xbar1 - test.x0))
        print_float_array('est. err', sqrt(varxbar1))
        print_float_array('bst. err', sqrt(varxbar1_bs))
        if not skipmbar:
            print_float_array('mbar means', xbar2)
            print_float_array('act. err', abs(xbar2 - test.x0))
            print_float_array('est. ett', sqrt(varxbar2))

    if dobench:
        for samples_per_state in (100, ):  #(50, 100, 400, 800):
            for nstates in (1000, ):  #(80, 160): #(10, 20, 40, 320):
                tu = Timer(
                    'test = HOSet(%d, %d, %f, %f); msmle = MSMLE(test.data, test.data_size); msmle.solve_uwham()'
                    % (nstates, samples_per_state, klow, kmax),
                    'from msmle import MSMLE; from hotest import HOSet')

                tm = Timer(
                    'test = HOSet(%d, %d, %f, %f); mbar = MBAR(test.data, test.data_size)'
                    % (nstates, samples_per_state, klow, kmax),
                    'from pymbar import MBAR; from hotest import HOSet')

                t1 = tu.timeit(1)
                t2 = tm.timeit(1)
                print nstates, samples_per_state, t1, t2, t2 / t1
Example #40
0
    # 2. translate all other characters to Soundex digits
    source = source.upper()
    digits = source[0] + "".join(
        map(lambda c: charToSoundex[c], source[1:])
    )  # 18.4: NOT faster than letter-wise dict lookup! due to "overhead of the anonymous lambda function"

    # 3. remove consecutive duplicates
    digits2 = digits[0]
    for d in digits[1:]:
        if digits2[-1] != d:
            digits2 += d

    # 4. remove all "9"s
    digits3 = re.sub('9', '', digits2)

    # 5. pad end with "0"s to 4 characters
    while len(digits3) < 4:
        digits3 += "0"

    # 6. return first 4 characters
    return digits3[:4]


if __name__ == '__main__':
    from timeit import Timer
    names = ('Woo', 'Pilgrim', 'Flingjingwaller')
    for name in names:
        statement = "soundex('%s')" % name
        t = Timer(statement, "from __main__ import soundex")
        print name.ljust(15), soundex(name), min(t.repeat())
Example #41
0
def function_to_run():
    s = 0
    for i in range(1000):
        s += i
        f = open("guru99.txt", "w+")
        f.write(str(s))
        f.close()


def show_results(func_name, results):
    print("%-23s %4.6f seconds" % (func_name, results))


if __name__ == '__main__':
    import sys
    from timeit import Timer

    repeat = 100
    number = 1
    num_threads = [1, 2, 4, 8]

print("start tersting")
for i in num_threads:
    t = Timer("non_threaded(%s)" % i, "from __main__ import non_threaded")
    best_result = min(t.repeat(repeat=repeat, number=number))
    show_results("non threaded (%s iters)" % i, best_result)

    t = Timer("threaded(%s)" % i, "from __main__ import threaded")
    best_result = min(t.repeat(repeat=repeat, number=number))
    show_results("threaded (%s iters)" % i, best_result)
    print('')
Example #42
0
        digits[i] = item
    del digits[i + 1:]
    digits2 = "".join(digits)
    digits3 = re.sub('9', '', digits2)
    while len(digits3) < 4:
        digits3 += "0"
    return digits3[:4]


if __name__ == '__main__':
    from timeit import Timer
    names = ('Woo', 'Pilgrim', 'Flingjingwaller')
    print("\n#\n# result of way 2")
    for name in names:
        statement = "soundex('%s')" % name
        t = Timer(statement, "from __main__ import soundex")
        print("# "), (name.ljust(15)), (soundex(name)), (min(
            t.repeat(20, 50000)))
    print("# "),

# 20 tests for 50000 each
# result of way 1a
# Woo             W000 0.44571715703
# Pilgrim         P426 0.479107457274
# Flingjingwaller F452 0.682555275898
# [Finished in 35.1s]
#
# result of way 3a
#  Woo             0000 0.238047519682
#  Pilgrim         4265 0.248714139275
#  Flingjingwaller 4525 0.327573558541
Example #43
0
# In[14]:

import zlib
s = b'witch which has which witches wrist watch'
len(s)

# In[15]:

t = zlib.compress(s)
len(t)

# In[16]:

zlib.decompress(t)

# In[17]:

zlib.crc32(s)

# In[18]:

from timeit import Timer
Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()

# In[19]:

Timer('a,b = b,a', 'a=1; b=2').timeit()

# In[ ]:
Example #44
0
# coding=utf-8

from timeit import Timer

print(Timer('t=a; a=b; b=t', 'a=1; b=2').timeit())
Example #45
0
def run(f):
    t1 = Timer(lambda: seq_sample(f))
    print('Sequential run')
    print(t1.repeat(repeat=3, number=1))

    t1 = Timer(lambda: thread_sample(f))
    print('Using threads')
    print(t1.repeat(repeat=3, number=1))

    t1 = Timer(lambda: process_sample(f))
    print('Using processes')
    print(t1.repeat(repeat=3, number=1))

    t1 = Timer(lambda: process_sample_group(f))
    print('Using processes (grouped data)')
    print(t1.repeat(repeat=3, number=1))
Example #46
0
from timeit import Timer

x = list(range(2000000))
pop_zero = Timer('x.pop(0)', 'from __main__ import x')
print('pop_zero', pop_zero.timeit(number=1000), 'millsseconds')

x = list(range(2000000))
pop_end = Timer('x.pop()', 'from __main__ import x')
print('pop_end', pop_end.timeit(number=1000), 'milliseconds')
Example #47
0
#!/usr/bin/env python
import sys
from timeit import Timer
from stations import locator

call = sys.argv[1]
print repr(call)
D = {}

for line in file('stations.dat'):
    c, l = [x.strip() for x in line.split(',')]
    D[c] = l

def test1(c):
    return D[c]

print repr(test1(call))
t = Timer("test1(%r)" % call, "from __main__ import test1")
print t.timeit()

# -----

def test2(c):
    return locator(c)

print repr(test2(call))
t = Timer("test2(%r)" % call, "from __main__ import test2")
print t.timeit()
Example #48
0
    print('Numba JIT, nopython with nogil')
    run(jit_nogil_func)

    try:
        import pyximport
        pyximport.install()
        import py_speed_cython

        print('Cython')
        run(py_speed_cython.func_slow)

        print('Cython, nogil')
        run(py_speed_cython.func_slow_nogil)

    except ImportError:
        print("Cython compiler not found. Skipping.")

    vec_auto_func = vectorize()(func_slow)
    t1 = Timer(lambda: vectorize_sample(vec_auto_func))
    print('Numba vectorize (default config, DUFunc)')
    print(t1.repeat(repeat=3, number=1))
    # [0.2374260425567627, 0.18294596672058105, 0.18335509300231934]

    vec_pl_func = vectorize(['int32(int32)', 'float64(float64)'],
                            target='parallel')(func_slow)
    t1 = Timer(lambda: vectorize_sample(vec_pl_func))
    print('Numba vectorize (target parallel)')
    print(t1.repeat(repeat=3, number=1))
    # [0.3076341152191162, 0.33128905296325684, 0.31762123107910156]
Example #49
0
    """
    return [_fizzbuzz(x) for x in range(1, n + 1)]


s = '''
def _fizzbuzz(x):
    if x % 15 == 0:
        return "FizzBuzz"
    elif x % 5 == 0:
        return "Buzz"
    elif x % 3 == 0:
        return "Fizz"
    else:
        return str(x)

def FizzBuzz(n):
    """ get fizzbuzz list

    Arguments:
    - `n`: integer, n > 0
    """
    return [_fizzbuzz(x) for x in range(1, n +1)]

FizzBuzz(10000)
'''


if __name__ == '__main__':
    t = Timer(stmt=s)
    print t.repeat(repeat=10, number=100)
Example #50
0
    def __init__(self,
                 n=[301, 501],
                 select=[
                     "all",
                 ],
                 n_max_bs=700,
                 n_max_slow=700,
                 transform_repeat=1):
        """
        Benchmark performance of different iAbel/fAbel implementations.

        Parameters
        ----------
        n: integer
            a list of arrays sizes for the benchmark
            (assuming 2D square arrays (n,n))

        select: list of str
            list of transforms to benchmark select=['all',] (default) or 
            choose transforms:
            select=['basex', 'direct_Python', 'direct_C', 'hansenlaw',
             'onion_bordas, 'onion_peeling', 'two_point', 'three_point']

        n_max_bs: integer
            since the basis sets generation takes a long time,
            do not run this benchmark for implementations that use basis sets
            for n > n_max_bs

        n_max_slow: integer
            maximum n run for the "slow" transform methods, so far including 
            only the "direct_python" implementation.
        """
        from timeit import Timer
        import time

        self.n = n

        transform = {
            'basex': basex.basex_core_transform,
            'basex_bs': basex.get_bs_basex_cached,
            'direct_Python': direct.direct_transform,
            'direct_C': direct.direct_transform,
            'hansenlaw': hansenlaw.hansenlaw_transform,
            'onion_bordas': onion_bordas.onion_bordas_transform,
            'onion_peeling': dasch.dasch_transform,
            'onion_peeling_bs': dasch._bs_onion_peeling,
            'two_point': dasch.dasch_transform,
            'two_point_bs': dasch._bs_two_point,
            'three_point': dasch.dasch_transform,
            'three_point_bs': dasch._bs_three_point,
        }

        # result dicts
        res = {}
        res['bs'] = {
            'basex_bs': [],
            'onion_peeling_bs': [],
            'two_point_bs': [],
            'three_point_bs': []
        }
        res['forward'] = {'direct_Python': [], 'hansenlaw': []}
        res['inverse'] = {
            'basex': [],
            'direct_Python': [],
            'hansenlaw': [],
            'onion_bordas': [],
            'onion_peeling': [],
            'two_point': [],
            'three_point': []
        }

        if direct.cython_ext:
            res['forward']['direct_C'] = []
            res['inverse']['direct_C'] = []

        # delete all keys not present in 'select' input parameter
        if "all" not in select:
            for trans in select:
                if trans not in res['inverse'].keys():
                    raise ValueError(
                        "'{}' is not a valid transform method".format(trans),
                        res['inverse'].keys())

            for direction in ['forward', 'inverse']:
                rm = []
                for abel in res[direction]:
                    if abel not in select:
                        rm.append(abel)
                for x in rm:
                    del res[direction][x]
            # repeat for 'bs' which has append '_bs'
            rm = []
            for abel in res['bs']:
                if abel[:-3] not in select:
                    rm.append(abel)
            for x in rm:
                del res['bs'][x]

        # ---- timing tests for various image sizes nxn
        for ni in n:
            ni = int(ni)
            x = np.random.randn(ni, ni)

            # basis set evaluation --------------
            basis = {}
            for method in res['bs'].keys():
                if method[:-3] == 'basex':  # special case
                    if ni <= n_max_bs:
                        # calculate and store basex basis matrix
                        t = time.time()
                        basis[method[:-3]] = transform[method](ni,
                                                               ni,
                                                               basis_dir=None)
                        res['bs'][method].append((time.time() - t) * 1000)
                    else:
                        basis[method[:-3]] = None,
                        res['bs'][method].append(np.nan)
                else:
                    # calculate and store basis matrix
                    t = time.time()
                    # store basis calculation. NB a tuple to accomodate basex
                    basis[method[:-3]] = transform[method](ni),
                    res['bs'][method].append((time.time() - t) * 1000)

            # Abel transforms ---------------
            for cal in ["forward", "inverse"]:
                for method in res[cal].keys():
                    if method in basis.keys():
                        if basis[method][0] is not None:
                            # have basis calculation
                            res[cal][method].append(
                                Timer(lambda: transform[method](x, *basis[
                                    method])).timeit(number=transform_repeat) *
                                1000 / transform_repeat)
                        else:
                            # no calculation available
                            res[cal][method].append(np.nan)
                    elif method[:6] == 'direct':  # special case 'direct'
                        if method[7] == 'P' and (ni > n_max_slow):
                            res[cal][method].append(np.nan)
                        else:
                            res[cal][method].append(
                                Timer(lambda: transform[method]
                                      (x, backend=method[7:], direction=cal
                                       )).timeit(number=transform_repeat) *
                                1000 / transform_repeat)
                    else:
                        # full calculation for everything else
                        res[cal][method].append(
                            Timer(lambda: transform[method](x, direction=cal)
                                  ).timeit(number=transform_repeat) * 1000 /
                            transform_repeat)

        self.fabel = res['forward']
        self.bs = res['bs']
        self.iabel = res['inverse']
Example #51
0
        return self.name < other.name if self.age == other.age else self.age < other.age

    def __eq__(self, other):
        return self.age == other.age


def selectionsort1(myarr):
    for i in range(len(myarr)):
        #求子数组[i,n)中的最小值对应的index
        min_index = i
        for j in range(i, len(myarr)):
            if myarr[j] < myarr[min_index]:
                min_index = j
        #交换list[i]与list[min_index]
        myarr[i], myarr[min_index] = myarr[min_index], myarr[i]

    return myarr


if __name__ == "__main__":
    array = [randint(0, 1000) for i in range(0, 1000)]
    timer = Timer('selectionsort1(array)',
                  'from __main__ import selectionsort1,array')
    print(timer.timeit(number=1))
    print('*' * 50)
    name_bank = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    array = [Student(choice(name_bank), randint(1, 100)) for _ in range(1000)]
    timer = Timer('selectionsort1(array)',
                  'from __main__ import selectionsort1,array')
    print(timer.timeit(number=1))
Example #52
0
 suite = unittest.TestLoader().loadTestsFromTestCase(PycteaTestCase64_1)
 unittest.TextTestRunner(verbosity=2).run(suite)
 print "EncryptStr 2"
 print "32 iterations:"
 suite = unittest.TestLoader().loadTestsFromTestCase(PycteaTestCase32_2)
 unittest.TextTestRunner(verbosity=2).run(suite)
 print "64 iterations:"
 suite = unittest.TestLoader().loadTestsFromTestCase(PycteaTestCase64_2)
 unittest.TextTestRunner(verbosity=2).run(suite)
 print ">>>>>>>>>>>>>>> Function Test End <<<<<<<<<<<<<<<"
 print ""
 print ">>>>>>>>>>>>> Performance Test Start <<<<<<<<<<<<"
 encrypted_string_en_32 = EncryptStr_1(string_unicode_en, key_unicode, 32)
 encrypted_string_en_64 = EncryptStr_1(string_unicode_en, key_unicode, 64)
 t1 = Timer(
     "EncryptStr_1(string_unicode_en, key_unicode, 32)",
     "from __main__ import EncryptStr_1, key_unicode, string_unicode_en")
 t2 = Timer(
     "DecryptStr_1(encrypted_string_en_32, key_unicode, 32)",
     "from __main__ import DecryptStr_1, key_unicode, encrypted_string_en_32"
 )
 print "EncryptStr_1 32 iterations:"
 print "Encrypt length(%s) chars string %s times: %s seconds" % (
     len(string_unicode_en), test_times, t1.timeit(test_times))
 print "Decrypt length(%s) chars string %s times: %s seconds" % (
     len(string_unicode_en), test_times, t2.timeit(test_times))
 t1 = Timer(
     "EncryptStr_2(string_unicode_en, key_unicode, 32)",
     "from __main__ import EncryptStr_2, key_unicode, string_unicode_en")
 t2 = Timer(
     "DecryptStr_2(encrypted_string_en_32, key_unicode, 32)",
Example #53
0
from timeit import Timer


def calculate(x, y):
    return x * y


if __name__ == '__main__':
    t = Timer("calculate(2, 34)", "from __main__ import  calculate")
    print t.timeit()
def main():
    t1 = Timer("test1()", "from __main__ import test1")
    print("concat ", t1.timeit(number=1000), "milliseconds")
    t2 = Timer("test2()", "from __main__ import test2")
    print("append ", t2.timeit(number=1000), "milliseconds")
    t3 = Timer("test3()", "from __main__ import test3")
    print("comprehension ", t3.timeit(number=1000), "milliseconds")
    t4 = Timer("test4()", "from __main__ import test4")
    print("list range ", t4.timeit(number=1000), "milliseconds")
Example #55
0
    # 5. pad end with "0"s to 4 characters

    while len(digits3) < 4:
        digits3 += "0"

    # 6. return first 4 characters
    return digits3[:4]


if __name__ == '__main__':
    from timeit import Timer
    names = ('Woo', 'Pilgrim', 'Flingjingwaller')
    for name in names:
        statement = "soundex('%s')" % name
        t = Timer(statement, "from __main__ import soundex")
        print(name.ljust(15)), (soundex(name)), (min(t.repeat(20, 50000)))

# 20 tests for 50000 each
# result of way 1
# Woo             W000 0.44571715703
# Pilgrim         P426 0.479107457274
# Flingjingwaller F452 0.682555275898
# [Finished in 35.1s]
# Woo             W000 0.347424399107
# Pilgrim         P426 0.480323836978
# Flingjingwaller F452 0.67085988562
# [Finished in 33.1s]
# Woo             W000 0.30222376214
# Pilgrim         P426 0.381320874233
# Flingjingwaller F452 0.654043631207
Example #56
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from timeit import Timer

print(
    min(
        Timer(setup="L = range(1000)",
              stmt="[i**2 for i in L]").repeat(10, 1000)),
    " ms per invocation")

print(
    min(
        Timer(setup="import numpy as np\na = np.arange(1000)",
              stmt="a**2").repeat(10, 1000)), " ms per invocation")
Example #57
0
 def test_time(self):
     rgb_depth = self.input_handler.handle()
     t = Timer(lambda: self.perception.perceive(rgb_depth))
     logging.info("SlowPerception runtime {} s".format(t.timeit(number=1)))
Example #58
0
    solution = solver.bestSolution
    #print("Current function value: %s" % solver.bestEnergy)
    #print("Iterations: %s" % solver.generations)
    #print("Function evaluations: %s" % solver.evaluations)

    print(solution)


if __name__ == '__main__':
    from numpy import inf
    print("without bounds...")
    from timeit import Timer
    print("Differential Evolution")
    print("======================")
    t = Timer("main()", "from __main__ import main")
    timetaken = t.timeit(number=1)
    print("CPU Time: %s\n" % timetaken)

    print("with bounds...")
    import time
    times = []
    algor = []

    print("Differential Evolution")
    print("======================")
    start = time.time()
    esow = Monitor()
    ssow = Monitor()
    #ssow= VerboseMonitor(1)
Example #59
0
push_a_yaxis = []
push_b_yaxis = []

range_a_yaxis = []
range_built_in_b_yaxis = []
range_simple_b_yaxis = []
range_pair_comparison_b_yaxis = []

xaxis = []

for i in range(100, 10100, 100):
    xaxis.append(i)

    # Fill in y axis for push runtimes
    a_time = Timer("""for x in range(""" + str(i) +
                   """): a.push((x - 5) ** 2)""",
                   setup="""import mystack; a = mystack.MyStack()""")
    push_a_yaxis.append(a_time.timeit(10) / 10)

    b_time = Timer("""for x in range(""" + str(i) +
                   """): b.push((x - 5) ** 2)""",
                   setup="""import myteststack; b = myteststack.MyStack()""")
    push_b_yaxis.append(b_time.timeit(10) / 10)

    # Fill in y axis for range lookup runtimes
    # Using time lib instead of timeit because of restrictions on having compound timeit setup statements
    # Will run each range function 10 times, time the runs and take the average
    a = mystack.MyStack()
    for x in range(i):
        a.push((x - 5)**2)
Example #60
0
import numpy as np
from timeit import Timer, default_timer as timer
import operator
import resource, random

rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
print('Soft limit starts as  :', soft)
resource.setrlimit(rsrc, (10000000000, hard))  #limit to one kilobyte
soft, hard = resource.getrlimit(rsrc)
print('Soft limit changed to :', soft)

N = 10000

nump_arr = np.ones([N, N])
nump_arr1 = np.ones([N, N])
li = nump_arr.tolist()
li1 = nump_arr1.tolist()


def python_for():
    return map(operator.__add__, li, li1)


def numpy_add():
    return nump_arr + nump_arr1


print(min(Timer(python_for).repeat(10, 10)))
print(min(Timer(numpy_add).repeat(10, 10)))