Пример #1
0
import timeit

if __name__ == '__main__':
    # 使用timeit计时
    t = timeit.Timer('??()', setup='from __main__ import ??')
    print(t.timeit(number=1))
Пример #2
0
    }
    '''
    list(t.tokenize(css))

#    c = {}
#    for x in t.tokenize(css):
#        n = x[0]
#        try:
#            c[n] += 1
#        except KeyError:
#            c[n] = 1
#    print c
    """
    t = cssutils.tokenize2.Tokenizer()

    t = timeit.Timer(do)  # outside the try/except
    try:
        print(t.timeit(100))  # or t.repeat(...)
    except Exception:
        print(t.print_exc())

    #    print cssutils.script.csscombine(p,
    #                                     resolveVariables=True)
    #    cssutils.ser.prefs.resolveVariables = True
    #    s = cssutils.parseFile(p)
    #    print s.cssRules
    #    print s.cssText
    sys.exit(1)


if 1:
    def test_ppq_cache_enabled_timeit(
        self,
        redirects_len: int,
        timeit_number: int,
        ppq_cache_max: int,
    ):
        """
        Test the `RedirectHandler._ppq_cache` is actually useful by timing the
        difference with and without via `ppq_cache_enabled` flag
        """
        time_start = time.time()
        RedirectHandler._ppq_cache_max = ppq_cache_max

        def _gen_redirects(redirects_len_: int) -> Re_Entry_Dict:
            """generate a `Re_Entry_Dict` of size `redirects_len_`."""
            redirects_ = Re_Entry_Dict_new()
            for i_ in range(0, redirects_len_):
                from_ = "/%08X" % i_
                to_ = "/%08X" % i_
                redirects_[Re_EntryKey(from_)] = Re_Entry(from_, to_)
            return redirects_

        # generate the redirects entries
        redirects = _gen_redirects(redirects_len)
        # create a small variety of lookups
        lookups = list()
        for l_ in (
            "/NO-MATCH1",
            #"/NO-MATCH2;f",
            #"/NO-MATCH3;f?a=A",
            #"/NO-MATCH4#foobar",
            # should match generated entries in `_gen_redirects`
            "/%08X" % 1,
            "/%08X?a=A" % 2,
            "/%08X#c" % 3,
            "/%08X?a=A&b=B#c" % 4,
            "/%08X?a=A&b=B#c" % int(redirects_len / 2),
            "/%08X?a=A&b=B#c" % (redirects_len - 2),
            "/%08X?a=A&b=B#c" % (redirects_len - 1),
        ):
            lookups.append((l_, urllib.parse.urlparse(l_),))

        # save `cache_enabled` setting
        cache_enabled_prev = RedirectHandler.ppq_cache_enabled

        print("", file=sys.stderr)
        results = {True: None, False: None}
        for cache_enabled in (True, False,):
            # set `cache_enabled` to test setting, clear cache
            RedirectHandler.ppq_cache_enabled = cache_enabled
            RedirectHandler.ppq_cache_clear()

            print("timeit(%4d) lookups len %d, redirects size %-5d, cache enabled %-5s: "
                  % (timeit_number, len(lookups), len(redirects),
                     RedirectHandler.ppq_cache_enabled,),
                  end="", file=sys.stderr)
            sys.stdout.flush()
            sys.stderr.flush()

            # timeit code
            def stmt_():
                for (ppq, ppqpr) in lookups:
                    __, ___ = RedirectHandler._do_VERB_redirect_processing(ppq, ppqpr, redirects)
            time1 = timeit.Timer(stmt=stmt_, globals=globals()).timeit(number=timeit_number)

            # print timeit results
            print("%1.6f" % (time1,), file=sys.stderr)
            sys.stdout.flush()
            sys.stderr.flush()
            # save timeit results for later assert
            results[cache_enabled] = time1
        # restore `cache_enabled` setting, clear cache
        RedirectHandler.ppq_cache_enabled = cache_enabled_prev
        RedirectHandler.ppq_cache_clear()
        time_stop = time.time()
        print("total time taken for test case %40s%1.6f" % ("", time_stop - time_start,), file=sys.stderr)
        # the cache disabled should be larger value (longer time; slower) than cache enabled
        assert results[False] > results[True]
Пример #4
0
        li.extend([i])


def text6():
    li = []
    for i in range(10000):
        li = li + [i]


def text7():
    li = []
    for i in range(10000):
        li.insert(0, i)


time1 = timeit.Timer('text1()', 'from __main__ import text1')
print('append:%.2f' % time1.timeit(number=1000))

time2 = timeit.Timer('text2()', 'from __main__ import text2')
print('+=:%.2f' % time2.timeit(number=1000))

time3 = timeit.Timer('text3()', 'from __main__ import text3')
print('[i for i in range]:%.2f' % time3.timeit(number=1000))

time4 = timeit.Timer('text4()', 'from __main__ import text4')
print('list(range):%.2f' % time4.timeit(number=1000))

time5 = timeit.Timer('text5()', 'from __main__ import text5')
print('extend:%.2f' % time5.timeit(number=1000))

time6 = timeit.Timer('text6()', 'from __main__ import text6')
Пример #5
0
import timeit


def test1():
    l1 = []
    for i in range(1, 10000):
        l1.append(i)


def test2():
    # 从尾部添加
    l1 = []
    for i in range(1, 10000):
        l1.insert(i - 1, i)


def test3():
    # 从头部添加
    l1 = []
    for i in range(1, 10000):
        l1.insert(0, i)


if __name__ == '__main__':
    timeit1 = timeit.Timer("test1()", "from __main__ import test1")
    timeit2 = timeit.Timer("test2()", "from __main__ import test2")
    timeit3 = timeit.Timer("test3()", "from __main__ import test3")
    print("append():", timeit1.timeit(1000))
    print("insert(i-1):", timeit2.timeit(1000))
    print("insert(0):", timeit3.timeit(1000))
Пример #6
0
from distutils.core import setup, Extension
from Cython.Distutils import build_ext
import sys

import Cython.Compiler.Options

#This will generate HTML to show where there are still pythonic bits hiding out
Cython.Compiler.Options.annotate = True

if len(sys.argv) == 1:
    sys.argv += ['build_ext','--inplace']

#Note: the name of the module MUST be the same as the name of the pure Python file
ext_modules = [Extension("test", ["test.py"]),
               ]

setup(
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules
)

import timeit
print timeit.Timer('test.f(0.3)','import test').timeit(10000000)
print timeit.Timer('test.g(0.3)','import test').timeit(10000000)
Пример #7
0
def decorator_without_try(func, num):
  def _wrapper(*args, **kwargs):
    func(num, *args, **kwargs)
  return _wrapper

def test_add(num):
  return num

test_decorator_with_try = decorator_with_try(test_add, 1)
test_decorator_without_try = decorator_without_try(test_add, 1)
test_bind = functools.partial(test_add, 1)

if __name__ == '__main__':
  import timeit

  t0 = timeit.Timer("test_add(1)",
                    "from __main__ import test_add")
  t1 = timeit.Timer("wrapper(test_add, 1)",
                    "from __main__ import test_add, wrapper")
  t2 = timeit.Timer("test_decorator_with_try()",
                    "from __main__ import test_decorator_with_try")
  t3 = timeit.Timer("test_decorator_without_try()",
                    "from __main__ import test_decorator_without_try")
  t4 = timeit.Timer("test_bind()",
                    "from __main__ import test_bind")
  t5 = timeit.Timer("functools.partial(test_add, 1)()",
                    "from __main__ import test_add, functools")
  loop_times = 3000000
  print t0.timeit(number=loop_times)
  print t1.timeit(number=loop_times)
  print t2.timeit(number=loop_times)
  print t3.timeit(number=loop_times)
Пример #8
0
        result_arr.extend(new_arr)

    return result_arr


if __name__ == '__main__':
    print("The merge sort algorithm")
    arr = [1, 3, 4, 7, 3, 5, 3, 8, 2, 1]

    new_arr = merge_sort(arr)
    print("Start:")
    pprint.pprint(arr)
    print("Result:")
    pprint.pprint(new_arr)

    # test a big random list
    big_list = [random.randint(0, 100) for _ in range(100)]
    big_list_sorted_by_merge = merge_sort(big_list)
    big_list_sorted_by_sorted = sorted(big_list)
    for x, y in zip(big_list_sorted_by_merge, big_list_sorted_by_sorted):
        assert x == y

    # time performance

    time = timeit.Timer(lambda: merge_sort(arr)).repeat(repeat=10, number=1)
    print("\nTime performance (10 items): ", sum(time) / len(time))

    time = timeit.Timer(lambda: merge_sort(big_list)).repeat(repeat=10,
                                                             number=1)
    print("\nTime performance (100 items): ", sum(time) / len(time))
Пример #9
0
                       help='optimize by loading c extensions')
argparser.add_argument('-d',
                       '--debug',
                       dest='debug',
                       action='store_true',
                       default=False,
                       help='verbose debug info')
args = argparser.parse_args()

thislocation = os.path.dirname(os.path.realpath(__file__))
svgpath = os.path.join(thislocation, 'test_svgs')


def main():
    # svgstring = open(os.path.join(svgpath, "full-bed.svg")).read()
    svgstring = open(os.path.join(svgpath, "rocket_full.svg")).read()
    # svgstring = open(os.path.join(svgpath, "rosetta.svg")).read()
    boundarys = read_svg(svgstring, [1220, 610], 0.08)


if args.profile:
    profile.run("main()", 'profile.tmp')
    p = pstats.Stats('profile.tmp')
    p.sort_stats('cumulative').print_stats(30)
    os.remove('profile.tmp')
elif args.timeit:
    t = timeit.Timer("main()", "from __main__ import main")
    print t.timeit(1)
    # print t.timeit(3)
else:
    main()
Пример #10
0
def time_nms_recommend_item_for_item():
    t = timeit.Timer("nms_idx.knnQuery(item_vectors[0])[0]")
    time = t.timeit(100)
    return time
Пример #11
0
naive = '''
for i in range(size):
    for j in range(size):
        for k in range(size):
            C[i + j*size] += A[i + k*size] * B[k + j*size]
           
'''
#Von j ist nur jsize abhängig, deswegen sollte diese Schleife ganz außen sein
#Von k ist neben ksize noch der Index c abhängig, weswegen die Schleife als zweite kommt
#Von i ist nun die eigentliche Operation abhängig, deswegen muss sie als letzte ausgeführt werden
optimised = '''
for j in range(size):
    jsize=j*size
    for k in range(size):
        ksize=k*size
        c=k + jsize
        for i in range(size):
            C[i + jsize] += A[i + ksize] * B[c]
   '''

repeats = 10
size = 100
t1 = timeit.Timer(naive, initialisation, globals=globals())
t2 = timeit.Timer(optimised, initialisation, globals=globals())
time1 = min(t1.repeat(repeats, 1))
print("execution time naive:", (time1 * 1000), "ms")
time2 = min(t2.repeat(repeats, 1))
print("execution time optimised:", (time2 * 1000), "ms")
print("Faster:", (1 - time2 / time1) * 100, "%")
#Die Komplexität ändert sich nicht, da die Hauptarbeit immer noch in den drei Schleifen steckt
Пример #12
0
def time_Annoy_recommend_item_for_item():
    t = timeit.Timer("temp_t.get_nns_by_vector(item_vectors[0], 10)")
    time = t.timeit(100)
    return time
Пример #13
0
def time_recommend_item_for_item():
    t = timeit.Timer(
        "recommend_item_for_item(item_vectors[0].reshape(1, -1), data, 10)")
    time = t.timeit(100)
    return time
    for i in range(1, len(parts)):
        jobs.append(r[:, parts[i - 1]:parts[i]])  # parallel jobs
    pool, out = mp.Pool(processes=numThreads), []
    outputs = pool.imap_unordered(barrierTouch, jobs)
    for out_ in outputs:
        out.append(out_)  # asynchronous respnse
    pool.close()
    pool.join()
    return


#-----------------
def barrierTouch(r, width=.5):
    #find the index of the earliest barrier touch
    t, p = {}, np.log((1 + r).cumprod(axis=0))
    for j in range(r.shape[1]):  # go through columns
        for i in range(r.shape[0]):  # go through rows
            if p[i, j] >= width or p[i, j] <= -width:
                t[j] = i
                continue
    return t


#---------------------
if __name__ == '__main__':
    import timeit
    print(
        min(
            timeit.Timer('main1()',
                         setup='from __main__ import main1').repeat(5, 10)))
Пример #15
0
#Test time and number of collisions for hash
import timeit
from universalhash import hash_func, probing_hash, linear_probing, quadratic_probing, test_univ_hash, funcs
#import universalhash



if __name__ == '__main__':
	coll_err_time = dict()
	
	for i, probfnc in enumerate(funcs):
		collision, errors = test_univ_hash(1000, hash_func=hash_func, probing_hash=probfnc)
		print(funcs[i])
		t = timeit.Timer("test_univ_hash(1000, hash_func = hash_func, \
			probing_hash=probfnc_index)",
		 "from universalhash import hash_func, probing_hash, linear_probing, quadratic_probing,\
		  test_univ_hash, funcs; probfnc_index=funcs[%i]"%(i))
		result = t.repeat(1, 2)
		print("Total time is %s"%max(result))
		coll_err_time[probfnc] = [collision, errors, max(result)]

	for key, item in coll_err_time.items():
		print("Function is %s"%key)
		print("Collisions, errors, max time is %s, %s, %s"%(item[0], item[1], item[2]))


	
Пример #16
0
    path = Path('/media/rahulrav/Cruzer/benchmark')

    # Recreate paths
    if os.path.exists(path.absolute().as_posix()):
        shutil.rmtree(path)

    inputs = ['input']
    types = ['int']
    tub = Tub(path.as_posix(), inputs, types, max_catalog_len=1000)
    write_count = 1000
    for i in range(write_count):
        record = {'input': i}
        tub.write_record(record)

    deletions = np.random.randint(0, write_count, 100)
    for index in deletions:
        index = int(index)
        tub.delete_record(index)
 
    for record in tub:
        print('Record %s' % record)

    tub.close()


if __name__ == "__main__":
    timer = timeit.Timer(benchmark)
    time_taken = timer.timeit(number=1)
    print('Time taken %s seconds' % time_taken)
    print('\nDone.')
Пример #17
0
import timeit
from Tests_Sorted.Time_test_sorted_integer_5000 import Array_sorted_integer_5000

f1=Array_sorted_integer_5000.sorted_integer_5000_100
f2=f1.copy()
f3=f1.copy()
f4=f1.copy()
f5=f1.copy()
f6=f1.copy()
f7=f1.copy()
f8=f1.copy()
f9=f1.copy()
f10=f1.copy()

#print("Random array\n",f1,"\n")
t=timeit.Timer(lambda : Python_Sort.python_sort(f1))
print("Python sort ",t.timeit(number = 1))
#print(f1,"\n")

t=timeit.Timer(lambda : Merge_Sort.merge_sort(f2))
print("Merge sort",t.timeit(number = 1))
#print(f2,"\n")

t=timeit.Timer(lambda : Comb_Sort.comb(f3))
print("Comb sort ",t.timeit(number = 1))
#print(f3,"\n")

t=timeit.Timer(lambda : Heap_Sort.heapSort(f4))
print("Heap sort ",t.timeit(number = 1))
#print(f4,"\n")
Пример #18
0
#!/usr/bin/python
#
# Sprawdzam szybkosc kolorowania wierzcholkow sp-grafu.
# Wydaje sie, ze grafy dwudzielne trafiaja sie bardzo rzadko.

import timeit
import random
from graphtheory.structures.edges import Edge
from graphtheory.structures.graphs import Graph
from graphtheory.seriesparallel.spnodes import Node
from graphtheory.seriesparallel.spnodecolor import SPNodeColoring
from graphtheory.seriesparallel.sptools import make_random_spgraph
from graphtheory.seriesparallel.sptools import make_random_ktree

V = 10
G = make_random_spgraph(V)
#G = make_random_ktree(V, 2)
E = G.e()
#G.show()

algorithm = SPNodeColoring(G)
algorithm.run()
all_colors = set(algorithm.color[node] for node in G.iternodes())
assert len(all_colors) == 3

print "Testing SPNodeColoring ..."
t1 = timeit.Timer(lambda: SPNodeColoring(G).run())
print V, E, t1.timeit(1)            # pojedyncze wykonanie

# EOF
Пример #19
0
    def timeit(self, line='', cell=None):
        """Time execution of a Python statement or expression

        Usage, in line mode:
          %timeit [-n<N> -r<R> [-t|-c]] statement
        or in cell mode:
          %%timeit [-n<N> -r<R> [-t|-c]] setup_code
          code
          code...

        Time execution of a Python statement or expression using the timeit
        module.  This function can be used both as a line and cell magic:

        - In line mode you can time a single-line statement (though multiple
          ones can be chained with using semicolons).

        - In cell mode, the statement in the first line is used as setup code
          (executed but not timed) and the body of the cell is timed.  The cell
          body has access to any variables created in the setup code.

        Options:
        -n<N>: execute the given statement <N> times in a loop. If this value
        is not given, a fitting value is chosen.

        -r<R>: repeat the loop iteration <R> times and take the best result.
        Default: 3

        -t: use time.time to measure the time, which is the default on Unix.
        This function measures wall time.

        -c: use time.clock to measure the time, which is the default on
        Windows and measures wall time. On Unix, resource.getrusage is used
        instead and returns the CPU user time.

        -p<P>: use a precision of <P> digits to display the timing result.
        Default: 3


        Examples
        --------
        ::

          In [1]: %timeit pass
          10000000 loops, best of 3: 53.3 ns per loop

          In [2]: u = None

          In [3]: %timeit u is None
          10000000 loops, best of 3: 184 ns per loop

          In [4]: %timeit -r 4 u == None
          1000000 loops, best of 4: 242 ns per loop

          In [5]: import time

          In [6]: %timeit -n1 time.sleep(2)
          1 loops, best of 3: 2 s per loop


        The times reported by %timeit will be slightly higher than those
        reported by the timeit.py script when variables are accessed. This is
        due to the fact that %timeit executes the statement in the namespace
        of the shell, compared with timeit.py, which uses a single setup
        statement to import function or create variables. Generally, the bias
        does not matter as long as results from timeit.py are not mixed with
        those from %timeit."""

        import timeit

        opts, stmt = self.parse_options(line,'n:r:tcp:',
                                        posix=False, strict=False)
        if stmt == "" and cell is None:
            return
        
        timefunc = timeit.default_timer
        number = int(getattr(opts, "n", 0))
        repeat = int(getattr(opts, "r", timeit.default_repeat))
        precision = int(getattr(opts, "p", 3))
        if hasattr(opts, "t"):
            timefunc = time.time
        if hasattr(opts, "c"):
            timefunc = clock

        timer = timeit.Timer(timer=timefunc)
        # this code has tight coupling to the inner workings of timeit.Timer,
        # but is there a better way to achieve that the code stmt has access
        # to the shell namespace?
        transform  = self.shell.input_splitter.transform_cell

        if cell is None:
            # called as line magic
            ast_setup = ast.parse("pass")
            ast_stmt = ast.parse(transform(stmt))
        else:
            ast_setup = ast.parse(transform(stmt))
            ast_stmt = ast.parse(transform(cell))

        ast_setup = self.shell.transform_ast(ast_setup)
        ast_stmt = self.shell.transform_ast(ast_stmt)

        # This codestring is taken from timeit.template - we fill it in as an
        # AST, so that we can apply our AST transformations to the user code
        # without affecting the timing code.
        timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
                                        '    setup\n'
                                        '    _t0 = _timer()\n'
                                        '    for _i in _it:\n'
                                        '        stmt\n'
                                        '    _t1 = _timer()\n'
                                        '    return _t1 - _t0\n')

        class TimeitTemplateFiller(ast.NodeTransformer):
            "This is quite tightly tied to the template definition above."
            def visit_FunctionDef(self, node):
                "Fill in the setup statement"
                self.generic_visit(node)
                if node.name == "inner":
                    node.body[:1] = ast_setup.body

                return node

            def visit_For(self, node):
                "Fill in the statement to be timed"
                if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
                    node.body = ast_stmt.body
                return node

        timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template)
        timeit_ast = ast.fix_missing_locations(timeit_ast)

        # Track compilation time so it can be reported if too long
        # Minimum time above which compilation time will be reported
        tc_min = 0.1

        t0 = clock()
        code = compile(timeit_ast, "<magic-timeit>", "exec")
        tc = clock()-t0

        ns = {}
        exec code in self.shell.user_ns, ns
        timer.inner = ns["inner"]

        if number == 0:
            # determine number so that 0.2 <= total time < 2.0
            number = 1
            for i in range(1, 10):
                if timer.timeit(number) >= 0.2:
                    break
                number *= 10

        best = min(timer.repeat(repeat, number)) / number

        print u"%d loops, best of %d: %s per loop" % (number, repeat,
                                                          _format_time(best, precision))
        if tc > tc_min:
            print "Compiler time: %.2f s" % tc
Пример #20
0
img.save('timing-shapes.png')

class0 = mapscript.classObj(ilayer)
class0.insertStyle(l.getClass(0).getStyle(0))
img = m.prepareImage()
ilayer.draw(m, img)
img.save('timing-inline.png')

# =========================================================================
# Test 1A: Draw all shapes at once using map.draw()

print("Test 1A: draw map, all shapes at once")
s = """\
img = m.draw()
"""
t = timeit.Timer(stmt=s, setup='from __main__ import m')
print("%.2f usec/pass" % (1000000 * t.timeit(number=100) / 100))

# =========================================================================
# Test 1B: Draw shape by shape from the shapefileObj

print("Test 1B: draw shapes one at a time")
s = """\
img = m.prepareImage()
for i in range(shpfile.numshapes):
    s = shpfile.getShape(i)
    s.classindex = 0
    s.draw(m, l, img)
"""
t = timeit.Timer(stmt=s, setup='from __main__ import m, l, shpfile')
print("%.2f usec/pass" % (1000000 * t.timeit(number=100) / 100))
            
        return self.arr
    def bubbleSort_threadChunk(self, i, n):
        swapped = False
        for j in range(0, len(n)-i-1, 1):
            if n[j] > n[j+1]:
                # Swap items
                n[j], n[j+1] = n[j+1], n[j]      
                swapped = True
                
        return [n, swapped]  

# Initialize class    
bubbleSort_ALGORITHM = bubbleSort()

pprint.pprint(
    bubbleSort_ALGORITHM.bubbleSort_withThreading(50),
    indent=100
)

bubbleSort_withThreading_TIMER = timeit.Timer("bubbleSort_ALGORITHM.bubbleSort_withThreading(5)", "from __main__ import bubbleSort_ALGORITHM")
bubbleSort_noThreading_TIMER = timeit.Timer("bubbleSort_ALGORITHM.bubbleSort_noThreading(5)", "from __main__ import bubbleSort_ALGORITHM")

for i in range(10):
    print()


repeat = eval(input("REPEAT > "))
pprint.pprint("BUBBLE SORT ALGORITHM WITH THREADING TIMING : {0}".format(bubbleSort_withThreading_TIMER.repeat(repeat=repeat, number=10000)), indent = 100)
pprint.pprint("BUBBLE SORT ALGORITHM NO THREADING TIMING : {0}".format(bubbleSort_noThreading_TIMER.timeit(repeat=repeat, number=10000)), indent = 100)
Пример #22
0
 def timer(f, functionParameters):
     return min(
         timeit.Timer(lambda: f(X)
                      if functionParameters == 1 else f(X, Xt)).repeat(
                          3, 100))
Пример #23
0
def time_it(description,
            stmt,
            setup,
            _globals,
            repeat,
            number,
            reference=None,
            check_dtype=None):
    """
    Measure execution of a specified statement which is useful for the
    performance analysis. In this way, the execution time and respective
    results can be directly compared.

    Parameters
    ----------
    description : str
        Descriptive name of configuration to be shown in the log
    stmt : str
        Statement to be timed
    setup : str
        Additional statement used for setup
    _globals :
        Namespace the code will be executed in (as opposed to inside timeit's
        namespace)
    repeat : int
        How many times to repeat the timeit measurement (results will be
        gathered as a list)
    number : int
        How many times to execute the statement to be timed
    reference : list of (float, any), optional
        Result with the same data structure as returned by this function,
        which will be referenced in order to compare execution time and
        similarity of the result data
    check_dtype : str, optional
        Data type of the result to check

    Returns
    -------
    (float, any)
        Tuple of execution time in seconds (minimum of all repetitions) and
        execution result of first repetition (data depends on the specified
        statement to be timed)
    """
    def _check_dtype(data_dtype):
        # check date type
        if data_dtype == check_dtype:
            _grade = "MATCH"
            _file = sys.stdout
        else:
            _grade = f"MISMATCH ({str(check_dtype)})"
            _file = sys.stderr
        print(f"result dtype: {str(data_dtype):>21} ... {_grade}", file=_file)
        sleep(0.05)  # to get correct output order

    print(description)

    # execute timed statement
    result = timeit.Timer(stmt=stmt, setup=setup,
                          globals=_globals).repeat(repeat=repeat,
                                                   number=number)
    # generate tuple of (time, evaluation result), whereby the kept time is
    # the minimum of all repetitions and the data is the result of the first
    # execution
    result = (min(list(zip(*result))[0]), result[0][1])

    # print conclusion
    print(f"time: {result[0]:-29.2f}s")
    sleep(0.05)  # to get correct output order

    if reference:
        t = result[0] / reference[0]
        file = sys.stdout
        if abs(t - 1) < 2e-2:
            grade = "EVEN"
        elif t < 1:
            grade = "BETTER"
        else:
            grade = "WORSE"
            file = sys.stderr
        print(f"time factor: {t:-22.2f} ... {grade}", file=file)
        sleep(0.05)  # to get correct output order

        if reference[1].shape != result[1].shape:
            if reference[1].shape == result[1].T.shape:
                # flip computation result, if matrices do not match
                reference = (reference[0], reference[1].T)
            else:
                print(
                    f"result shape: {str(result[1].shape):>21s}"
                    f" ... MISMATCH {str(reference[1].shape)}",
                    file=sys.stderr,
                )
                sleep(0.05)  # to get correct output order

                if check_dtype:
                    _check_dtype(result[1].dtype)
                print()
                return result

        r = np.abs(np.sum(np.subtract(result[1], reference[1])))
        file = sys.stdout
        if r == 0:
            grade = "PERFECT"
        elif r < 1e-10:
            grade = "OKAY"
        else:
            grade = "MISMATCH"
            file = sys.stderr
        print(f"result sum:  {r:-22} ... {grade}", file=file)
        sleep(0.05)  # to get correct output order

        r = np.abs(np.subtract(result[1], reference[1])).max()
        file = sys.stdout
        if r == 0:
            grade = "PERFECT"
        elif r < 1e-10:
            grade = "OKAY"
        else:
            grade = "MISMATCH"
            file = sys.stderr
        print(f"result max:  {r:-22} ... {grade}", file=file)
        sleep(0.05)  # to get correct output order

    if check_dtype:
        _check_dtype(result[1].dtype)
    print()
    return result
Пример #24
0
    opts, args = getopt.getopt(sys.argv[1:], "ahb:",
                               ["all", "help", "backbars=", "start=", "end="])
    if len(args) > 0:
        start = 0
        end = 0
        for o, a in opts:
            if o in ("-h", "--help"):
                print csvtolist.__doc__
                sys.exit()
            elif o in ("-b", "--backbars"):
                import pprint
                #pprint.pprint(csvtolist(args[0],int(a)))
                #print csvtolist(args[0],int(a))
                import timeit
                tt = timeit.Timer("csvtolist('%s',%d)" % (args[0], int(a)),
                                  "from __main__ import csvtolist")
                print "Run csvtolist once take ", tt.timeit(500) / 500
            elif o in ("-a", "--all"):
                print csvtolist(args[0], maxbars=True)
            elif o in ("--start"):
                start = a
            elif o in ("--end"):
                end = a

        if start or end:
            print csvtolist(args[0], start=start, end=end)

    else:
        print csvtolist.__doc__
        sys.exit()
Пример #25
0
    def test_lists(self):
        organizations_query = '''
        {{
          ...OrganizationList_organizations_1tT5Hu
          ...OrganizationList_organization_types
        }}

        fragment OrganizationList_organization_types on Query {{
          getChoicesForDropdown(name: "organization_types") {{
            name
            value
            id
          }}
        }}

        fragment OrganizationList_organizations_1tT5Hu on Query {{
          organizations(filter: {filter}, orderBy: {order_by}) {{
            edges {{
              node {{
                handle_id
                ...OrganizationRow_organization
                id
                __typename
              }}
              cursor
            }}
            pageInfo {{
              hasNextPage
              endCursor
            }}
          }}
        }}

        fragment OrganizationRow_organization on Organization {{
          handle_id
          name
          type
          organization_id
          affiliation_customer
          affiliation_end_customer
          affiliation_host_user
          affiliation_partner
          affiliation_provider
          affiliation_site_owner
          parent_organization {{
            organization_id
            id
          }}
          incoming {{
            name
            relation {{
              type
              start {{
                handle_id
                node_name
                id
              }}
              id
            }}
          }}
        }}
        '''

        # order by id: native django order
        by_id_query = organizations_query.format(filter={},
                                                 order_by='handle_id_DESC')
        setup_code = self.setup_code.format(query_value=by_id_query)

        mark1 = timeit.Timer("""result = schema.execute(query, context=context); assert result.data""", \
            setup=setup_code).timeit(1)

        test_result = "Organization list resolution with default order took {} seconds\n".format(
            mark1)
        self.write_to_log_file(test_result)

        # order by id: native django order
        name_query = organizations_query.format(filter={},
                                                order_by='name_DESC')
        setup_code = self.setup_code.format(query_value=name_query)
        mark2 = timeit.Timer("""result = schema.execute(query, context=context); assert result.data""", \
            setup=setup_code).timeit(1)

        test_result = "Organization list resolution with name order took {} seconds\n".format(
            mark2)
        self.write_to_log_file(test_result)

        contacts_query = '''
        query SearchContactsAllQuery{{
          ...ContactList_contacts_1tT5Hu
          ...ContactList_organization_types
          ...ContactList_roles_default
        }}

        fragment ContactList_contacts_1tT5Hu on Query {{
          contacts(filter: {filter}, orderBy: {order_by}) {{
            edges {{
              node {{
                handle_id
                ...ContactRow_contact
                id
                __typename
              }}
              cursor
            }}
            pageInfo {{
              endCursor
              hasNextPage
              hasPreviousPage
              startCursor
            }}
          }}
        }}

        fragment ContactList_organization_types on Query {{
          getChoicesForDropdown(name: "organization_types") {{
            name
            value
            id
          }}
        }}

        fragment ContactList_roles_default on Query {{
          getRolesFromRoleGroup {{
            handle_id
            name
          }}
        }}

        fragment ContactRow_contact on Contact {{
          handle_id
          first_name
          last_name
          contact_type
          modified
          roles {{
            name
            end {{
              name
              id
            }}
          }}
        }}
        '''

        # order by id: native django order
        by_id_query = contacts_query.format(filter={},
                                            order_by='handle_id_DESC')
        setup_code = self.setup_code.format(query_value=by_id_query)

        mark1 = timeit.Timer("""result = schema.execute(query, context=context); assert result.data""", \
            setup=setup_code).timeit(1)

        test_result = "Contact list resolution with default order took {} seconds\n".format(
            mark1)
        self.write_to_log_file(test_result)

        # order by id: native django order
        name_query = contacts_query.format(filter={}, order_by='name_DESC')
        setup_code = self.setup_code.format(query_value=name_query)
        mark2 = timeit.Timer("""result = schema.execute(query, context=context); assert result.data""", \
            setup=setup_code).timeit(1)

        test_result = "Contact list resolution with name order took {} seconds\n".format(
            mark2)
        self.write_to_log_file(test_result)

        groups_query = '''
        query SearchGroupAllQuery{{
          ...GroupList_groups_1tT5Hu
        }}

        fragment GroupList_groups_1tT5Hu on Query {{
          groups(filter: {filter}, orderBy: {order_by}) {{
            edges {{
              node {{
                handle_id
                ...GroupRow_group
                id
                __typename
              }}
              cursor
            }}
            pageInfo {{
              hasNextPage
              endCursor
            }}
          }}
        }}

        fragment GroupRow_group on Group {{
          handle_id
          name
          description
        }}
        '''

        # order by id: native django order
        by_id_query = groups_query.format(filter={}, order_by='handle_id_DESC')
        setup_code = self.setup_code.format(query_value=by_id_query)

        mark1 = timeit.Timer("""result = schema.execute(query, context=context); assert result.data""", \
            setup=setup_code).timeit(1)

        test_result = "Group list resolution with default order took {} seconds\n".format(
            mark1)
        self.write_to_log_file(test_result)

        # order by id: native django order
        name_query = groups_query.format(filter={}, order_by='name_DESC')
        setup_code = self.setup_code.format(query_value=name_query)
        mark2 = timeit.Timer("""result = schema.execute(query, context=context); assert result.data""", \
            setup=setup_code).timeit(1)

        test_result = "Group list resolution with name order took {} seconds\n".format(
            mark2)
        self.write_to_log_file(test_result)
                     'Numpy': np.sort}

for input_ordering in ['sorted', 'reverse', 'random']:
    for input_size in range(1, 8):
        test_data = np.random.random((10 ** input_size,))
        if input_ordering == 'sorted':
            test_data = sorted(test_data)
        elif input_ordering == 'reverse':
            test_data = list(reversed(sorted(test_data)))

        for sorting_name, sorting_function in sorting_functions.items():
            quicksort_recursion_error = sorting_name == 'Quicksort' and ((input_ordering == 'sorted' or input_ordering == 'reverse') and input_size > 2)

            if not quicksort_recursion_error:
                clock = timeit.Timer(stmt='sort_func(copy(data))',
                                     globals={'sort_func': sorting_function,
                                              'data': test_data,
                                              'copy': copy.copy})

                n_ar, t_ar = clock.autorange()
                t = clock.repeat(repeat=7, number=n_ar)
                print(
                    f"{sorting_name} minimum time on {input_ordering} data of size 10^{input_size}:",
                    min(t))

                for run_number in range(7):
                    results = results.append({'Input ordering': input_ordering,
                                              'Input size': 10 ** input_size,
                                              'Run number': run_number + 1,
                                              'Sorting algorithm': sorting_name,
                                              'Time': t[run_number]},
                                             ignore_index=True)
Пример #27
0
80.
import random

print(random.randrange(7,15))

81.
import zlib
string="hello world!hello world!hello world!hello world!"
byt=bytes(string,"utf-8")
print(zlib.compress(byt))
print(zlib.decompress(byt))

82.
import timeit

t=timeit.Timer("for i in range(100):1+1")
print(t.timeit())

83.
import random 

li=[3,6,7,8]
random.shuffle(li)
print(li)

84.
subject=["I","You"]
verb=["Play", "Love"]
object=["Hockey", "Football"]
for s in subject:
    for v in verb:
Пример #28
0
import dis
import inspect
import timeit

programs = dict(
    loop="""
multiples_of_two = []
for x in range(100):
	if x % 2 == 0:
		multiples_of_two.append(x)
""",
    comprehension='multiples_of_two = [x for x in range(100) if x % 2 == 0]',
)

for name, text in programs.iteritems():
    print name, timeit.Timer(stmt=text).timeit()
    code = compile(text, '<string>', 'exec')
    dis.disassemble(code)
Пример #29
0
import numpy as np
from scipy import linalg
import timeit

m, n = 50, 50
A = np.random.rand(m, n)
B = np.random.rand(m, n)


def my_func1():
    X1 = linalg.solve(A, B)


def my_func2():
    X2 = np.dot(linalg.inv(A), B)


t1 = timeit.Timer(stmt=my_func1).timeit(number=100)
t2 = timeit.Timer(stmt=my_func2).timeit(number=100)
print(t1, t2)
Пример #30
0
def timeout_handler(signum, frame):
    raise Timeout()


signal.signal(signal.SIGALRM, timeout_handler)

NUMBER = 10
REPEAT_COUNT = 3
TIMEOUT = 10
SIZE_LIST = [10, 1024, 2 * 1024, 100 * 1024, 1024 * 1024]

timers = {
    'pyhtml2text':
    timeit.Timer(
        'html2text(html)',
        setup='from pyhtml2text import html2text; from __main__ import html'),
    'html2text':
    timeit.Timer(
        'h.handle(html)',
        setup=
        'import html2text as python_html2text; h = python_html2text.HTML2Text();  from __main__ import html'
    ),
    'bs4+html.parser':
    timeit.Timer(
        'BeautifulSoup(html, "html.parser").get_text()',
        setup='from bs4 import BeautifulSoup; from __main__ import html'),
    'bs4+lxml':
    timeit.Timer(
        'BeautifulSoup(html, "lxml").get_text()',
        setup='from bs4 import BeautifulSoup; from __main__ import html'),