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)
Beispiel #2
0
def main():
    t = Timer( 'euler14()', "from __main__ import euler14" )

    try:
        print t.timeit( 1 )
    except:
        print t.print_exc()
Beispiel #3
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)
Beispiel #4
0
    def bench(self, width):
        def execSilx():
            medfilt2d_silx(self.img, width)

        def execScipy():
            scipy.ndimage.median_filter(input=self.img,
                                        size=width,
                                        mode='nearest')

        def execPymca():
            medfilt2d_pymca(self.img, width)

        execTime = {}

        t = Timer(execSilx)
        execTime["silx"] = t.timeit(BenchmarkMedianFilter.NB_ITER)
        logger.info(
            'exec time silx (kernel size = %s) is %s' % (width, execTime["silx"]))

        if scipy is not None:
            t = Timer(execScipy)
            execTime["scipy"] = t.timeit(BenchmarkMedianFilter.NB_ITER)
            logger.info(
                'exec time scipy (kernel size = %s) is %s' % (width, execTime["scipy"]))
        if pymca is not None:
            t = Timer(execPymca)
            execTime["pymca"] = t.timeit(BenchmarkMedianFilter.NB_ITER)
            logger.info(
                'exec time pymca (kernel size = %s) is %s' % (width, execTime["pymca"]))

        return execTime
Beispiel #5
0
def main():

    # Listing 3
    t1 = Timer(stmt="test1()", setup="from __main__ import test1")
    print ("concat ", t1.timeit(number=1000), "milliseconds")

    t2 = Timer(stmt="test2()", setup="from __main__ import test2")
    print ("concat ", t2.timeit(number=1000), "milliseconds")

    t3 = Timer(stmt="test3()", setup="from __main__ import test3")
    print ("concat ", t3.timeit(number=1000), "milliseconds")

    t4 = Timer(stmt="test4()", setup="from __main__ import test4")
    print ("concat ", t4.timeit(number=1000), "milliseconds")

    # Listing 4
    popzero = timeit.Timer("x.pop(0)", "from __main__ import x")
    popend = timeit.Timer("x.pop()", "from __main__ import x")

    print "popzero ", popzero.timeit(number=1000)
    x = list(range(2000000))
    print "popend ", popend.timeit(number=1000)


    # Listing 5
    print ("pop(0) pop()")
    for i in range(1000000,10000001,1000000):
        x = list(range(i))
        pt = popend.timeit(number=1000)
        x = list(range(i))
        pz = popzero.timeit(number=1000)
        print ("%15.5f, %15.5f" %(pz, pt))
Beispiel #6
0
def write_effective():
    from timeit import Timer
    print "start to test"
    #t1=Timer("write_file_only()",setup="from __main__ import write_file_only");
    t1=Timer("write_file_andif()",setup="from __main__ import write_file_andif");
    #打印执行XX次函数的时间
    print t1.timeit(100000)
Beispiel #7
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)
Beispiel #8
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)
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))
Beispiel #10
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))
Beispiel #11
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 test_array():
    from timeit import Timer

    m = Timer("arraytest()", "from __main__ import arraytest")
    n = Timer("enumeratetest()", "from __main__ import enumeratetest")

    print m.timeit()  # 5.22479210582
    print n.timeit()  # 4.34367196717
Beispiel #13
0
def main2():
    popzero = Timer("x.pop(0)",
                        "from __main__ import x")
    popend = Timer("x.pop()",
                        "from __main__ import x")
    print(popzero.timeit(number=1000))
    # 1.5798413809989142
    print(popend.timeit(number=1000))
Beispiel #14
0
def main():
    parse_command_line()
    t = Timer(e1)
    results = t.timeit(options.num) / options.num
    print 'engine: %0.3f ms per iteration' % (results * 1000)
    t = Timer(c1)
    results = t.timeit(options.num) / options.num
    print 'coroutine: %0.3f ms per iteration' % (results * 1000)
Beispiel #15
0
 def setUp(self):
     #print(groffle_faster(mass, density))
     self.groffle_slow = groffle_slow(mass, density)
     self.groffle_faster = groffle_faster(mass, density)
     slowtime = Timer("total = groffle_slow(mass, density)", "from __main__ import groffle_slow, mass, density")
     fastertime = Timer("total = groffle_faster(mass, density)", "from __main__ import groffle_faster, mass, density")
     self.slowtime = slowtime.timeit(number=1000)
     self.fasttime = fastertime.timeit(number=1000)
Beispiel #16
0
def compare_ve_conds2():
    """Runs a comparison of naive and non-naive variable elimination
    when there's conditioning"""
    from timeit import Timer
    for naive in (True,False):
        veti = Timer("asia.copy(True).condition({'Cancer':['absent'],'TbOrCa':['false']}).variable_elimination(['VisitAsia','Tuberculosis', 'XRay','Dyspnea', 'Bronchitis', 'Smoking','TbOrCa'],%s)" % naive,
                     "from gPy.Examples import asia")
        print 'Time taken with naive = %s:' % naive
        print veti.timeit(1000)
def TestSpeed(Sizes=np.logspace(1,7),SizeNaiveCutoff=5e4):
    """
    Speed tests everything

    Args:
       Sizes: to test the FFT-based cross correlation
       SizeNaiveCutoff: when the naive cross correlation is cutoff
    """
    from timeit import Timer
    times = []
    timesNaive = []
    sizesNaive = []
    for j,size in enumerate(Sizes):
        # get the data and shift it
        x,y = GetSampleFEC(size)
        _,_,YShifted,YNoise,_ = \
                AddNoiseAndShift(x,y,SliceFract=0.1)
        t = Timer(lambda: \
                  NormalizedCorrelation(YNoise,YShifted,
                                        CorrelationFunc=FFTCrossCorrelation))
        # get the expected convolution times
        BestTime = t.timeit(number=5)
        times.append(BestTime)
        # see if we should record naive data
        if (size < SizeNaiveCutoff):
            t = Timer(lambda: \
                NormalizedCorrelation(YNoise,YShifted,
                                      CorrelationFunc=NaiveCrossCorrelation))
            NaiveTime = t.timeit(number=5)
            timesNaive.append(NaiveTime)
            sizesNaive.append(size)
    # remained is just for plotting the results
    interpX = lambda x: np.linspace(min(x),max(x),
                                    len(x)*100)
    size_naive_interp = interpX(sizesNaive)
    # fit a quadratic to the naive
    coeffs = np.polyfit(x=sizesNaive,y=timesNaive,deg=2)
    quad = np.polyval(coeffs,size_naive_interp)
    # fit nlogn to the fft
    mFunc = lambda x,c: c*x*np.log(x)
    pOpt,_ = curve_fit(mFunc,xdata=Sizes,ydata=times,p0=1)
    # interpolate along sizes
    size_fft_interp = interpX(Sizes)
    nLogN = mFunc(size_fft_interp,*pOpt)
    fig = plt.figure()
    plt.loglog(Sizes,times,'ro',label="FFT Convolution")
    plt.loglog(sizesNaive,timesNaive,'bx',label="Naive Convolution")    
    plt.loglog(size_naive_interp,quad,'k--',label="O(n^2)")
    plt.loglog(size_fft_interp,nLogN,'r-',label="O(nlog(n))")
    plt.ylabel("Time (seconds)")
    plt.xlabel("Input Size (Number of Points)")
    plt.title("Naive convolution is O(n^2)")
    plt.legend(loc='upper left')
    MaxT= max(max(timesNaive),max(times))
    MinT = min(min(timesNaive),min(times))
    plt.ylim([min(times),MaxT])
    fig.savefig("./OutTimeTrials.png")
Beispiel #18
0
def main1():
    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")
Beispiel #19
0
def test_timeit():
    from timeit import Timer

    t1 = Timer("test_readlines()", setup='from __main__ import test_readlines;print "readlines test"')
    r1 = t1.timeit(5)
    print r1  # * 1000

    t2 = Timer("test_readline()", setup='from __main__ import test_readline;print "readline test"')
    r2 = t2.timeit(5)
    print r2  # * 1000
Beispiel #20
0
def benchmark():
	import json, sys
	from timeit import Timer
	from jsfetch import search

	chunk = search( "i'll", 2, 1, 1 )
	t1 = Timer( "analyseSongList( chunk )", "from joysound import analyseSongList; chunk = '''%s'''" % (chunk,) )
	t2 = Timer( "analyseSongList( chunk )", "from joysound2 import analyseSongList; chunk = '''%s'''" % (chunk,) )
	print t1.timeit( 10 ) # 4.2660381794
	print t2.timeit( 10 ) # 0.319856882095
Beispiel #21
0
def main():
    t1 = Timer('pri(1000)', 'from __main__ import pri')
    t2 = Timer('pri_2(1000)', 'from __main__ import pri_2')
    t3 = Timer('pri_3(1000)', 'from __main__ import pri_3')
    t4 = Timer('pri_4(1000)', 'from __main__ import pri_4')

    print(t1.timeit(1))
    print(t2.timeit(1))
    print(t3.timeit(1))
    print(t4.timeit(1))
def main():
    fp = open("testkeys.txt", "w")
    fp.write(repr(keys))
    fp.close()
    print("Nodes: %d" % len(keys))

    t = Timer("bintree_build()", setup_BinaryTree_b)
    print_result(t.timeit(COUNT), "BinaryTree build only")

    t = Timer("avl_build()", setup_AVLTree_b)
    print_result(t.timeit(COUNT), "AVLTree build only")

    t = Timer("rb_build()", setup_RBTree_b)
    print_result(t.timeit(COUNT), "RBTree build only")

    t = Timer("bintree_build_delete()", setup_BinaryTree_bd)
    print_result(t.timeit(COUNT), "BinaryTree build & delete")

    t = Timer("avl_build_delete()", setup_AVLTree_bd)
    print_result(t.timeit(COUNT), "AVLTree build & delete")

    t = Timer("rb_build_delete()", setup_RBTree_bd)
    print_result(t.timeit(COUNT), "RBTree build & delete")

    shuffle(keys)

    t = Timer("bintree_search()", setup_BinaryTree_s)
    print_result(t.timeit(COUNT), "BinaryTree search")

    t = Timer("avl_search()", setup_AVLTree_s)
    print_result(t.timeit(COUNT), "AVLTree search")

    t = Timer("rb_search()", setup_RBTree_s)
    print_result(t.timeit(COUNT), "RBTree search")
Beispiel #23
0
def test_compressed_dna_performance():
    setup = "from biopsy.gapped_pssms import TestCompressedDnaSeq; test = TestCompressedDnaSeq( 10000000 )"
    number = 10
    from timeit import Timer

    t = Timer("test.test_char()", setup)
    print "Char:", t.timeit(number=number)
    t = Timer("test.test_unsigned()", setup)
    print "Unsigned:", t.timeit(number=number)
    t = Timer("test.test_compressed()", setup)
    print "Compressed:", t.timeit(number=number)
def benchmark(func_name):
    from timeit import Timer
    n = 10**5
    setup = '''from __main__ import %s''' % func_name
    proc = func_name + '''('Start^xX part^yY part^zEnd',%r)'''
    arg = 'x'
    t = Timer(proc % arg, setup)
    print(proc % arg, t.timeit(n))
    arg = '*'
    t = Timer(proc % arg, setup)
    print(proc % arg, t.timeit(n))
Beispiel #25
0
def speed_test():
    from timeit import Timer
    t = Timer("factorial_recursive(10)",
              "from factorial import factorial_recursive")
    print "Recursive:", t.timeit(10000)
    t = Timer("factorial_nonrecursive(10)",
              "from factorial import factorial_nonrecursive")
    print "Non-recursive:", t.timeit(10000)
    t = Timer("factorial_numpy(10)",
              "from factorial import factorial_numpy")
    print "Numpy factorial:", t.timeit(10000)
Beispiel #26
0
    def timer_routine(self, pyfftw_callable, numpy_fft_callable, comparison_string="numpy.fft"):

        N = 100

        t = Timer(stmt=pyfftw_callable)
        t_numpy_fft = Timer(stmt=numpy_fft_callable)

        t_str = ("%.2f" % (1000.0 / N * t.timeit(N))) + " ms"
        t_numpy_str = ("%.2f" % (1000.0 / N * t_numpy_fft.timeit(N))) + " ms"

        print("One run: " + t_str + " (versus " + t_numpy_str + " for " + comparison_string + ")")
Beispiel #27
0
def test_fast_versus_slow():
    df = pd.DataFrame({"Sample": "001", "epitope": ["AAAAL"] * 1000, "iedb_epitope": ["AGGGT"] * 1000})
    from timeit import Timer

    slow_timer = Timer(lambda: calculate_similarity_from_df(df, ignore_seqalign=True))
    slow_time = slow_timer.timeit(number=3)
    fast_timer = Timer(lambda: calculate_similarity_from_df(df, ignore_seqalign=False))
    fast_time = fast_timer.timeit(number=3)
    ok_(
        slow_time > fast_time * 5,
        ("The fast similarity calculation (%0.2f) should be at least " "5x faster than the slower version (%0.2f).")
        % (fast_time, slow_time),
    )
Beispiel #28
0
def compare_ves():
    """Demo showing time taken for variable elimination with 2 different
    elimination orders"""
    from timeit import Timer
    for order in (
        ['VisitAsia', 'Tuberculosis', 'XRay',  'Dyspnea', 'Bronchitis', 
         'Smoking', 'TbOrCa'],
        ['TbOrCa', 'VisitAsia', 'Tuberculosis', 'XRay', 'Bronchitis', 
         'Smoking', 'Dyspnea']):
        veti = Timer("asia.copy(True).variable_elimination(%s)" % order,
                     "from gPy.Examples import asia")
        print 'Time taken for 1000 iterations of variable elimination using order %s:' % order
        print veti.timeit(1000)
Beispiel #29
0
 def setUp(self):       
     mass = 2.5
     density = 12
     self.slow_answer = groffle_slow(mass, density)
     self.fast_answer = groffle_fast(mass, density)
     
     sTimer = Timer("total = groffle_slow(mass, density)", 
     "from groffle import groffle_slow, mass, density") 
     self.slow = sTimer.timeit(number=1000)
     
     fTimer = Timer("total = groffle_fast(mass, density)", 
     "from groffle import groffle_fast, mass, density") 
     self.fast = fTimer.timeit(number=1000)
Beispiel #30
0
 def speedup(mintime, fn1, args1, fn2, args2):
     i1 = i2 = 0
     n = 10
     t1 = Timer(lambda: fn1(*args1))
     t2 = Timer(lambda: fn2(*args2))
     while (i1 < mintime and i2 < mintime) or i2 < 1e-6:
         i1 = t1.timeit(n)
         i2 = t2.timeit(n)
         n *= 2
     warn = '' if i1 >= i2 else '  *** slowdown ***'
     si1 = '%.6g' % (i1,)
     si2 = '%.6g' % (i2,)
     return "%10s -> %-10s (%.3gx)%s" % (si1, si2, float(i1)/i2, warn)
Beispiel #31
0
from pymnet import *
from timeit import Timer

### ER with large number of layers


def create_er():
    net = er(10, 10**5 * [0.1])
    return net


timer = Timer(create_er)
result = timer.timeit(number=100)

### ER with large number of nodes


def create_er2():
    net = er(10**5, 10 * [10**-5])
    return net


timer2 = Timer(create_er2)
result2 = timer2.timeit(number=100)

### Aggregating ER

net = er(10**5, 10 * [10**-5])


def aggr():
Beispiel #32
0
# Exercise 81
# Level 1
# written by: Vince Mao
# last modified: 2019.6.6
# Description:
# Please write a program to print the runtime execution of  printing"1+1" 100 times.
#
# Hint:
# Use the timeit() module to measure the runtime.
# Use the Timer method to measure the runtime.
#
# Pseudocode:
# 1. Import time.
# 2. Use the timeit() module and the Timer function with proper syntax to print the runtime execution.

from timeit import Timer

test = Timer("for i in range(100): 1 + 1")
print test.timeit()
Beispiel #33
0
"""
为进一步论证这些操作表现的差异性,让我们用timeit模块进行另一个实验。
我们的目标是能够核实以下两种pop操作的表现,第一种是在一个已知长度的列表中从列表的末端删除元素,而第二种则是从这个列表的开头删除元素。
我们还想测量出对不同长度的列表进行pop操作的时间。
我们想要看到的是,随着列表长度的增加,从列表末端删除元素的pop操作时间保持稳定,而从列表开头删除元素的pop操作则随着长度的增加而增加。

下面的代码展示了对这两种pop操作的区别进行测量的一个尝试。正如你从第一个例子中看见的那样,
从列表末尾删除的pop操作耗时 0.00009 秒,然而从列表开头删除则耗时 1.40275 秒。
对于一个有2百万个元素的列表,两种操作耗费的时间相差 14000 倍。
"""

from timeit import Timer

pop_zero = Timer('x.pop(0)', 'from __main__ import x')
pop_end = Timer('y.pop()', 'from __main__ import y')

x = list(range(2000000))
print('%15.10f' % pop_zero.timeit(number=1000))

y = list(range(2000000))
print('%15.10f' % pop_end.timeit(number=1000))
"""
   1.4027522290
   0.0000952200
"""
Beispiel #34
0
from timeit import Timer
from fibo_functions import *

t1 = Timer("fib(10)", "from fibo_functions import fib")

for i in range(1, 41):
    s = "fib(" + str(i) + ")"
    t1 = Timer(s, "from fibo_functions import fib")
    time1 = t1.timeit(3)
    s = "fibi(" + str(i) + ")"
    t2 = Timer(s, "from fibo_functions import fibi")
    time2 = t2.timeit(3)
    print("n=%2d, fib: %8.6f, fibi:  %7.6f, percent: %10.2f" %
          (i, time1, time2, time1 / time2))

t3 = Timer("fib(10)", "from fibo_functions import fib")

for i in range(1, 41):
    s = "fibm(" + str(i) + ")"
    t3 = Timer(s, "from fibo_functions import fibm")
    time3 = t3.timeit(3)
    s = "fibi(" + str(i) + ")"
    t4 = Timer(s, "from fibo_functions import fibi")
    time4 = t4.timeit(3)
    print("n=%2d, fib: %8.6f, fibi:  %7.6f, percent: %10.2f" %
          (i, time3, time4, time3 / time4))
Beispiel #35
0
from timeit import Timer
t = Timer("for i in range(100):1+1")
print(t.timeit())
Beispiel #36
0
def benchmarker():
    ### variables that are used by the unholy, hellish, monster, demon that is
    ### the timeit module, may it it be drawn and quartered, burned, and its
    ### ashes scattered to the seven seas.
    global nameList
    global benchmarkSim
    global benchmarkTime
    global benchmarkPerson

    #benchmarkPerson = nameList[0]
    benchmarkTime = randDate(convertDateString(STARTDATE),
                             convertDateString(ENDDATE))
    setrecursionlimit(10000)  # increase recursion depth to allow timeit to
    # to work its foul, unnatural magic

    #masterList = copy.deepcopy(nameList)

    ### timeit's wipping boy
    benchmarkSim = CrimeDBSim(nameList[:1], preLoadPercent=1)

    # holds insertion times
    insertion = []

    ### timer for insertion benchmarks
    t = Timer(
        "benchmarkInsert(benchmarkTime,benchmarkPerson)",
        "from __main__ import benchmarkInsert; from __main__ import benchmarkTime; from __main__ import benchmarkPerson"
    )

    ###run insertion benchmarks
    for i in range(50, 2000, 1):
        benchmarkSim = CrimeDBSim(nameList[:i + 1], preLoadPercent=1)
        #shuffle(nameList)
        benchmarkPerson = randPerson(nameList[i + 1:])
        insertion.append(t.timeit(1))
        print(benchmarkSim.DB.length())
    #print(insertion)

    # retrieval times
    get = []

    ### timer for retrieval benchmarks
    t = Timer(
        "benchmarkGet(benchmarkTime,benchmarkPerson)",
        "from __main__ import benchmarkGet; from __main__ import benchmarkTime; from __main__ import benchmarkPerson"
    )

    benchmarkSim = CrimeDBSim(nameList[:1], preLoadPercent=1)
    ###run retrieval benchmarks
    for i in range(50, 2000, 1):
        benchmarkSim = CrimeDBSim(nameList[:i + 1], preLoadPercent=1)
        benchmarkPerson = randPerson(nameList[:i + 1])
        get.append(t.timeit(1))
        print(benchmarkSim.DB.length())

    # deletion times
    deletion = []

    ### timer for  retrieval benchmarks
    t = Timer(
        "benchmarkDelete(benchmarkTime,benchmarkPerson)",
        "from __main__ import benchmarkDelete; from __main__ import benchmarkTime; from __main__ import benchmarkPerson"
    )
    benchmarkSim = CrimeDBSim(nameList[:1], preLoadPercent=1)
    ### run deletion benchmarks
    for i in range(2000):
        benchmarkSim = CrimeDBSim(nameList[:i + 1], preLoadPercent=1)
        benchmarkPerson = randPerson(nameList[:i + 1])
        deletion.append(t.timeit(1))
        print(benchmarkSim.DB.length())
    #print(get)

    ###WARNING: I have only been able to get this to work in 2.7, it is untested
    ### with python 3.x, disabled by default
    if plotBenchmarks:
        plt.figure(1)
        p1, = plt.plot(insertion)
        plt.xlabel('Database Size')
        plt.ylabel('Time for 1 insertions')
        plt.title('Insertion Benchmark')

        plt.figure(2)
        p2, = plt.plot(get)
        plt.xlabel('Database Size')
        plt.ylabel('Time for 1 retrievals')
        plt.title('Retrieval Benchmark')

        plt.figure(3)
        p3, = plt.plot(deletion)
        plt.xlabel('Database Size')
        plt.ylabel('Time for 1 deletion')
        plt.title('Deletion Benchmark')
        plt.show()
    return n if n == 0 else n + nsum(n - 1)


@memorize
# 返回斐波那契数列的第n个数
def fib(n):
    assert (n >= 0), "n must be >=0"
    return n if n in (0, 1) else fib(n - 1) + fib(n - 2)


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

    measures = [
        {
            "exec": "fib(100)",
            "import": "fib",
            "func": fib
        },
        {
            "exec": "nsum(100)",
            "import": "nsum",
            "func": nsum
        },
    ]
    for item in measures:
        t = Timer(item["exec"],
                  "from __main__ import {}".format(item["import"]))
        print("name: {}, doc: {}, executing: {}, time:{}". \
           format(item["func"].__name__, item["func"].__doc__, item["exec"], t.timeit()))
from numpy import arange
from timeit import Timer

size = 1000000
timeits = 1000

# below creates an ndarray with values 0->size -1
nd_array = arange(size - 1)
print(type(nd_array))

# Timer expects the operation as a parameter
# here we pass nd_array.sum()
timer_numpy = Timer("nd_array.sum()", "from __main__ import nd_array")
print('Time taken by nump ndarray: %f seconds' %
      (timer_numpy.timeit(timeits) / timeits))

# below we compare how long a list takes for the same computation
a_list = list(range(size))
print(type(a_list))

# here we pass sum(a_list) in to Timer
timer_list = Timer("sum(a_list)", "from __main__ import a_list")
print('Time taken by list: %f seconds' %
      (timer_list.timeit(timeits) / timeits))
Beispiel #39
0
        my_lst.append(i)


# списковое включение
# list comprehension
def test_lst_comp():
    my_lst = [i for i in range(1000)]


# встроенная функция range
def test_range():
    my_lst = list(range(1000))


t1 = Timer("test_concat()", "from __main__ import test_concat")
print("list concat ", t1.timeit(number=1000), "seconds")

t2 = Timer("test_cycle()", "from __main__ import test_cycle")
print("list append ", t2.timeit(number=1000), "seconds")

t3 = Timer("test_lst_comp()", "from __main__ import test_lst_comp")
print("list comprehension ", t3.timeit(number=1000), "seconds")

t4 = Timer("test_range()", "from __main__ import test_range")
print("list range ", t4.timeit(number=1000), "seconds")

"""
concat  1.1779784 seconds
append  0.0715625000000002 seconds
comprehension  0.033750200000000063 seconds
range  0.011227300000000273 seconds
def test1():
    list1 = []
    for i in range(1000):
        list1 = list1 + [i]


def test2():
    list2 = []
    for i in range(1000):
        list2.append(i)


def test3():
    list3 = [i for i in range(1000)]


def test4():
    list4 = list(range(1000))


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

t2 = Timer("test2()", "from __main__ import test2")
print("append:", t2.timeit(number=10000), "milliseconds")

t3 = Timer("test3()", "from __main__ import test3")
print("Comprehension:", t3.timeit(number=10000), "milliseconds")

t4 = Timer("test4()", "from __main__ import test4")
print("range:", t4.timeit(number=10000), "milliseconds")
Beispiel #41
0
# -*- coding: utf-8 -*-
def test1():
    "built-in function"
    aList = range(100)
    return sum(aList)


def test2():
    "home-code function1"
    aList = range(100)
    return reduce(lambda x, y: x + y, aList)


def test3():
    "home-code function2"
    temp = 0
    for i in range(100):
        temp = temp + i
    return temp


if __name__ == '__main__':
    from timeit import Timer
    t1 = Timer("test1()", "from __main__ import test1")
    t2 = Timer("test2()", "from __main__ import test2")
    t3 = Timer("test3()", "from __main__ import test3")
    print "built-in function consume:" + str(t1.timeit(number=10000)) + ' s'
    print "home code function1 consume:" + str(t2.timeit(number=10000)) + ' s'
    print "home code function2 consume:" + str(t3.timeit(number=10000)) + ' s'
Beispiel #42
0
    #  下面的代码都是根据我的这个数据库来的,就是为了验证算法准确性,如果大家改了实例,请更改下面的代码
    nameList = [
        '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12',
        '13', '14', '15'
    ]
    characteristic = [
        'centerlight', 'glasses', 'happy', 'normal', 'leftlight', 'noglasses',
        'rightlight', 'sad', 'sleepy', 'surprised', 'wink'
    ]
    for c in characteristic:
        count = 0
        for i in range(len(nameList)):
            # 这里的loadname就是我们要识别的未知人脸图,我们通过15张未知人脸找出的对应训练人脸进行对比来求出正确率
            loadname = 'D:\python/face recongnition\YALE\YALE\unpadded\subject' + nameList[
                i] + '.' + c + '.pgm'
            judgeImg = cv2.imread(loadname, 0)
            if judgeFace(mat(judgeImg).flatten(), LBPoperator,
                         exHistograms) + 1 == int(nameList[i]):
                count += 1
        print
        'accuracy of %s is %f' % (c, float(count) / len(nameList))  # 求出正确率


if __name__ == '__main__':
    # 测试这个算法的运行时间
    from timeit import Timer

    t1 = Timer("runLBP()", "from __main__ import runLBP")
    t1.timeit(1)
Beispiel #43
0
    solver.SetRandomInitialPoints(min=[0.] * ND, max=[5.] * ND)
    solver.SetEvaluationLimits(generations=MAX_GENERATIONS)

    solver.Solve(CostFunction, termination=VTR(0.0000001), strategy=Rand1Exp, \
                 CrossProbability=0.3, ScalingFactor=1.0)

    solution = solver.Solution()

    print(solution)


if __name__ == '__main__':
    from timeit import Timer
    t = Timer("main()", "from __main__ import main")
    timetaken = t.timeit(number=1)
    print("CPU Time: %s" % timetaken)

    from mystic.monitors import Monitor
    from mystic.solvers import NelderMeadSimplexSolver as fmin
    from mystic.termination import CandidateRelativeTolerance as CRT

    import random
    simplex = Monitor()
    esow = Monitor()
    xinit = [random.uniform(0, 5) for j in range(ND)]

    solver = fmin(len(xinit))
    solver.SetInitialPoints(xinit)
    solver.SetEvaluationMonitor(esow)
    solver.SetGenerationMonitor(simplex)
Beispiel #44
0
f = ActiveMQConnectionFactory('tcp://localhost:61613?wireFormat=stomp')
conn = f.createConnection()
session = conn.createSession(AcknowledgeMode.DUPS_OK_ACKNOWLEDGE)
queue = session.createQueue('arrays')
consumer = session.createConsumer(queue)
producer = session.createProducer(queue)
producer.deliveryMode = DeliveryMode.NON_PERSISTENT
conn.start()

def test():
    for i in xrange(npickles):
        m = session.createBytesMessage()
        # pickle array into BytesMessage's body
        m.bodyBytes = x.dumps()
        producer.send(m)
        m2 = consumer.receive(1000)
        assert m2 is not None
        # unpickle array from BytesMessage's body
        y = N.loads(m2.bodyBytes)
        assert_array_equal(x, y)

from timeit import Timer
t = Timer('test()', 'from __main__ import test')
delta = t.timeit(1)

conn.close()

mibps = npickles * x.nbytes / (1024.0 * 1024.0) / delta
print 'pickled %d arrays, each %d bytes, in %f seconds (%.4f MiB/s)' % \
    (npickles, x.nbytes, delta, mibps)
        return
    else:
        traverse(LEFTMOST_CHILD(n, T), T)
        tmp = LEFTMOST_CHILD(n, T)
        tmp = RIGHT_SIBLING(tmp, T)
        while tmp is not None:
            traverse(tmp, T)
            tmp = RIGHT_SIBLING(tmp, T)


def derp():
    gTree = buildTree(0, n)
    traverse(ROOT(gTree), gTree)


MAXNODES = 500
NUMREPS = 1000

gTree = tree()

for n in range(0, 5):
    print "----- n = ", n, " -----"

    t = Timer("herp()", "from __main__ import herp")
    buildtime = t.timeit(NUMREPS) / (NUMREPS)  # NUMREPS executions
    print "Time to build tree of size    ", n, ":\t", buildtime

    t = Timer("derp()", "from __main__ import derp")
    travtime = t.timeit(NUMREPS) / (NUMREPS)  # NUMREPS executions
    print "Time to traverse tree of size ", n, ":\t", travtime - buildtime
Beispiel #46
0
    for i in range(2, n + 1):
        result *= i
    return result


print(iterative_factorial(5))

from timeit import Timer
#from fibo import factorial

t1 = Timer("factorial(10)", "from fibo import factorial")

for i in range(1, 20):
    s = "factorial(" + str(i) + ")"
    t1 = Timer(s, "from fibo import factorial")
    time1 = t1.timeit(3)
    s = "iterative_factorial(" + str(i) + ")"
    t2 = Timer(s, "from fibo import iterative_factorial")
    time2 = t2.timeit(3)
    print(
        "n=%2d, factorial: %8.6f, iterative_factorial:  %7.6f, percent: %10.2f"
        % (i, time1, time2, time1 / time2))


def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)