python类timeit()的实例源码

test_timeit.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def repeat(self, stmt, setup, repeat=None, number=None):
        self.fake_timer = FakeTimer()
        t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer)
        kwargs = {}
        if repeat is None:
            repeat = DEFAULT_REPEAT
        else:
            kwargs['repeat'] = repeat
        if number is None:
            number = DEFAULT_NUMBER
        else:
            kwargs['number'] = number
        delta_times = t.repeat(**kwargs)
        self.assertEqual(self.fake_timer.setup_calls, repeat)
        self.assertEqual(self.fake_timer.count, repeat * number)
        self.assertEqual(delta_times, repeat * [float(number)])

    # Takes too long to run in debug build.
    #def test_repeat_default(self):
    #    self.repeat(self.fake_stmt, self.fake_setup)
packages.py 文件源码 项目:asn1tools 作者: eerimoq 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def libsnmp_encode_decode():
    try:
        import libsnmp.rfc1905 as libsnmp_rfc1905

        def decode():
            libsnmp_rfc1905.Message().decode(ENCODED_MESSAGE)

        encode_time = float('inf')
        decode_time = timeit.timeit(decode, number=ITERATIONS)
    except ImportError:
        encode_time = float('inf')
        decode_time = float('inf')
        print('Unable to import libsnmp.')
    except SyntaxError:
        encode_time = float('inf')
        decode_time = float('inf')
        print('Syntax error in libsnmp.')

    return encode_time, decode_time
packages.py 文件源码 项目:asn1tools 作者: eerimoq 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def pyasn1_encode_decode():
    try:
        from pysnmp.proto import api
        from pyasn1.codec.ber import decoder

        snmp_v1 = api.protoModules[api.protoVersion1].Message()

        def decode():
            decoder.decode(ENCODED_MESSAGE, asn1Spec=snmp_v1)

        encode_time = float('inf')
        decode_time = timeit.timeit(decode, number=ITERATIONS)
    except ImportError:
        encode_time = float('inf')
        decode_time = float('inf')
        print('Unable to import pyasn1.')

    return encode_time, decode_time
test_suite.py 文件源码 项目:cypunct 作者: jamesmishra 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_benchmark(self):
        """Benchmark our code against a regex baseline."""
        baseline_speed = timeit.timeit(
            "baseline.split(testcase)",
            setup=TEST_SETUP,
            number=self.bench_iterations,
        )
        cypunct_speed = timeit.timeit(
            "cypunct.split(testcase)",
            setup=TEST_SETUP,
            number=self.bench_iterations,
        )
        print(
            "\nBenchmark results: ({0} loops)\n\n".format(
                self.bench_iterations))
        print("baseline speed:", baseline_speed, sep="\t")
        print("cypunct speed:", cypunct_speed, sep="\t")
conv1d.py 文件源码 项目:deep-hashtagprediction 作者: jderiu 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_kmax_pooling_time():
  nbatches, nkernels_in, nwords, ndim = 50, 16, 58, 300
  input_shape = (nbatches, nkernels_in, nwords, ndim)

  input = T.tensor4('input')

  k = 1
  f_kmax_argsort = theano.function([input], k_max_pooling(input, k))
  f_kmax_unroll = theano.function([input], _k_max_pooling(input, k))
  f_max = theano.function([input], max_pooling(input))

  image_data = np.random.randn(*input_shape).astype(dtype=np.float64)
  # np.random.shuffle(image_data)
  image_data = image_data.reshape(input_shape)
  # print image_data
  # print 'kmax'
  print 'f_kmax_argsort', timeit.timeit(lambda: f_kmax_argsort(image_data), number=10)
  print 'f_kmax_unroll', timeit.timeit(lambda: f_kmax_unroll(image_data), number=10)
  print 'f_max', timeit.timeit(lambda: f_max(image_data), number=10)
conv1d.py 文件源码 项目:CQA-CNN 作者: 3141bishwa 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_kmax_pooling_time():
  nbatches, nkernels_in, nwords, ndim = 50, 16, 58, 300
  input_shape = (nbatches, nkernels_in, nwords, ndim)

  input = T.tensor4('input')

  k = 1
  f_kmax_argsort = theano.function([input], k_max_pooling(input, k))
  f_kmax_unroll = theano.function([input], _k_max_pooling(input, k))
  f_max = theano.function([input], max_pooling(input))

  image_data = np.random.randn(*input_shape).astype(dtype=np.float64)
  # np.random.shuffle(image_data)
  image_data = image_data.reshape(input_shape)
  # print image_data
  # print 'kmax'
  print 'f_kmax_argsort', timeit.timeit(lambda: f_kmax_argsort(image_data), number=10)
  print 'f_kmax_unroll', timeit.timeit(lambda: f_kmax_unroll(image_data), number=10)
  print 'f_max', timeit.timeit(lambda: f_max(image_data), number=10)
debug.py 文件源码 项目:nlp-playground 作者: jamesmishra 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def easy_timer(code_to_benchmark, *, repeat=3, number=1000):
    """
    Wrap timeit.Timer().repeat() to catch locals.

    Rather than put our setup statement in a string for
    :py:func:`timeit.timeit`, we can just pull locals and globals
    from the calling stack frame.

    Args:
        code_to_benchmark(str): A string containing the Python code
            that we want to benchmark.

        repeat(int): Number of times to repeat the timer trial.

        number(int): Number of iterations **per** trial.

    Returns:
        (float): The best measured time of ``repeat`` times.

    """
    timer = timeit.Timer(stmt=code_to_benchmark, globals=copy_environment(2))
    best_time = min(timer.repeat(repeat=repeat, number=number))
    return best_time
debug.py 文件源码 项目:nlp-playground 作者: jamesmishra 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def print_easy_timer(code_to_benchmark, *, repeat=3, number=1000):
    """
    Repeatedly time code and print results.

    Args:
        code_to_benchmark(str): A string containing the Python code
            that we want to benchmark.

        repeat(int): Number of times to repeat the timer trial.

        number(int): Number of iterations **per** trial.

    Returns:
        (float): The best measured time of ``repeat`` times.

    """
    timer = timeit.Timer(stmt=code_to_benchmark, globals=copy_environment(2))
    best_time = min(timer.repeat(repeat=repeat, number=number))
    print(":\t\t".join((
        code_to_benchmark,
        str(best_time)
    )))
    return best_time
benchmark.py 文件源码 项目:welcome-bench 作者: faassen 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def run(frameworks, number, do_profile):
    print("Benchmarking frameworks:", ', '.join(frameworks))
    sys.path[0] = '.'
    path = os.getcwd()
    print("                ms     rps  tcalls  funcs")
    for framework in frameworks:
        os.chdir(os.path.join(path, framework))
        try:
            main = __import__('app', None, None, ['main']).main

            f = lambda: list(main(environ.copy(), start_response))
            time = timeit(f, number=number)
            st = Stats(profile.Profile().runctx(
                'f()', globals(), locals()))
            print("%-11s %6.0f %7.0f %7d %6d" % (framework, 1000 * time,
                  number / time, st.total_calls, len(st.stats)))
            if do_profile:
                st = Stats(profile.Profile().runctx(
                    'timeit(f, number=number)', globals(), locals()))
                st.strip_dirs().sort_stats('time').print_stats(10)
            del sys.modules['app']
        except ImportError:
            print("%-15s not installed" % framework)
timer.py 文件源码 项目:ComplexityEstimator 作者: marwin1991 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def measure_time(self):
        logger = init_logger("measure_time")
        logger.info("Begin measure time")
        loaded_module = SourceFileLoader(
            self.module_name,
            self.path_to_module).load_module()
        all_functions = inspect.getmembers(loaded_module, inspect.isfunction)

        fun_names = []
        for i in all_functions:
            fun_names.append(i[0])

        if self.function_to_measure.split("(")[0] not in fun_names:
            logger.info("ArgFunNameError raised because "
                        "of no function with this name")
            logger.debug(self.function_to_measure.split("(")[0])
            logger.debug(all_functions)
            raise ArgFunNameError

        returns_values_list = []
        init_struct_code_copy = self.init_struct_code
        for i in range(0, self.repeats):
            setup = "from {0} import {1}; {2}"\
                .format(self.module_name, self.function_to_measure.split("(")[0],
                        init_struct_code_copy)

            @exit_after(self.timeout)
            def __inside_measure():

                returns_values_list.append(
                    timeit.timeit(self.function_to_measure, setup=setup,
                                  number=1))
            __inside_measure()
            logger.debug(init_struct_code_copy)
            logger.info("Times loop: " + str(i))
            init_struct_code_copy = add_step(init_struct_code_copy, self.step)
        logger.info(returns_values_list)
        logger.info("End measure time")
        return returns_values_list
statistics.py 文件源码 项目:mau-mau 作者: obestwalter 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def durations(self, reps=1000):
        """calculate durations for <reps> games"""
        timing = timeit(
            setup="from mau_mau.play import play_game;"
                  "from mau_mau.rules import MauMau;"
                  "mmRules = MauMau()",
            stmt="play_game(mmRules, 3)",
            number=reps)
        log.info("it takes %0.3f seconds to play %s games", timing, reps)
cPyparsing_test.py 文件源码 项目:cpyparsing 作者: evhub 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def bench_func(func, n=10):
    """Benchmark the given function."""
    return timeit(func, number=n) / n
test_timeit.py 文件源码 项目:core-python 作者: yidao620c 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def my_timeit():
    cdeque = """
import collections
s = collections.deque()
"""
    t1 = timeit("s.appendleft(37)", cdeque, number=100000)
    t2 = timeit("s.insert(0, 37)",
                "s=[]", number=100000)
    print("t1=", t1)
    print("t2=", t2)
    pass
time_function.py 文件源码 项目:base_function 作者: Rockyzsu 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def timeit_usage():
    start=time.clock()
    print timeit.timeit('test_func()','from __main__ import test_func',number=10000)
    end=time.clock()
    print end-start
dataFrame_test.py 文件源码 项目:base_function 作者: Rockyzsu 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def misc():
    vals1 = np.array([1, np.nan, 3, 4])
    print vals1.sum()

    for dtype in ['object', 'int']:
        print("dtype =", dtype)
        # print timeit.timeit(np.arange(1E6, dtype=dtype).sum())
        start = time.time()
        print np.arange(1E8, dtype=dtype).sum()

        print time.time()-start
bench_pairing.py 文件源码 项目:ecpy 作者: elliptic-shiho 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def main():
  l = 2201426263
  p = 6 * l - 1
  F = ExtendedFiniteField(p, "x^2+x+1")
  E = EllipticCurve(F, 0, 1)
  i = 3
  while True:
    y = E.get_corresponding_y(i)
    if y != None:
      P = E(i, y)
      if (l * P).is_infinity():
        break
    i += 1
  print(P)

  rand = [randint(2**31, 2**32) for _ in xrange(10)]
  count = 20

  weil_time = []
  print("[+] Weil Pairing: ")
  for x in rand:
    r = timeit("bench_pairing.do_test()",
               setup="import bench_pairing; from ecpy import EllipticCurve, ExtendedFiniteField; bench_pairing.init_test('weil', [%r, %r, %r.distortion_map(), %r])" % (E, P, x*P, l),
               number=count)
    weil_time += [r]
    show_results("weil", r, count)

  print("[+] Tate Pairing: ")
  tate_time = []
  for x in rand:
    r = timeit("bench_pairing.do_test()",
               setup="import bench_pairing; from ecpy import EllipticCurve, ExtendedFiniteField; bench_pairing.init_test('tate', [%r, %r, %r.distortion_map(), %r, 2])" % (E, P, x*P, l), number=count)
    tate_time += [r]
    show_results("tate", r, count)

  print("=" * 64)
  show_results("weil", sum(weil_time), count * 10)
  show_results("tate", sum(tate_time), count * 10)
speed_decoding.py 文件源码 项目:raiden 作者: raiden-network 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def run_timeit(message_name, message, iterations=ITERATIONS):
    data = message.encode()

    def test_encode():
        message.encode()

    def test_decode():
        decode(data)

    encode_time = timeit.timeit(test_encode, number=iterations)
    decode_time = timeit.timeit(test_decode, number=iterations)

    print('{}: encode {} decode {}'.format(message_name, encode_time, decode_time))
identify.py 文件源码 项目:Library-Identification 作者: Riscure 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def benchmark(rdb, sample, refs):
    """
    Basic benchmarking function, call with a reference db `rdb`, a `sample`
    and a list of `refs`.
    """

    def bench1():
        return [compare_strings_concat_levenshtein(sample, ref)
                for ref in refs]

    def bench2():
        return [compare_strings_set_union(sample, ref)
                for ref in refs]
    def bench3():
        return [compare_cc_list_levenshtein(sample, ref)
                for ref in refs]

    def bench4():
        return [compare_cc_list_set_union(sample, ref)
                for ref in refs]

    def bench5():
        return [compare_cc_spp(sample, ref)
                for ref in refs]

    def bench6():
        return [compare_bb_hash_bloomfilter(sample, ref)
                for ref in refs]

    # Only run the slow ones a few times, and cc3 only once because of caching
    t1 = timeit.timeit(lambda: bench1(), setup="gc.enable()", number=5) / 5.0
    t2 = timeit.timeit(lambda: bench2(), setup="gc.enable()", number=100) / 100.0
    t3 = timeit.timeit(lambda: bench3(), setup="gc.enable()", number=100) / 100.0
    t4 = timeit.timeit(lambda: bench4(), setup="gc.enable()", number=100) / 100.0
    t5 = timeit.timeit(lambda: bench5(), setup="gc.enable()", number=1) / 1.0
    t6 = timeit.timeit(lambda: bench6(), setup="gc.enable()", number=100) / 100.0

    print(t1, t2, t3, t4, t5, t6)
et312-baud-rate.py 文件源码 项目:buttshock-py 作者: metafetish 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def main():
    global et312
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--port", dest="serial_port",
                        help="Serial Port to use")

    args = parser.parse_args()

    if not args.serial_port:
        print("Serial port argument is required!")
        sys.exit(1)

    with buttshock.et312.ET312SerialSync(args.serial_port) as et312:
        et312.perform_handshake()
        key = et312.key
        print("Key is {0:#x} ({0})".format(et312.key, et312.key))

        current_baud_rate = et312.get_baud_rate()
        print("Current baud flag: {:#02x}".format(current_baud_rate))
        print("Running 1000 mode gets test")
        # Get the current mode
        print("Total time: {}", timeit.timeit(stmt=read_mode, number=1000))
    print("Shifting baud rate")
    with buttshock.et312.ET312SerialSync(args.serial_port,
                                         key=key,
                                         shift_baud_rate=True) as et312:
        print("Running 1000 mode gets test")
        print("Total time: {}", timeit.timeit(stmt=read_mode, number=1000))
test_timeit.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __init__(self, seconds_per_increment=1.0):
        self.count = 0
        self.setup_calls = 0
        self.seconds_per_increment=seconds_per_increment
        timeit._fake_timer = self


问题


面经


文章

微信
公众号

扫码关注公众号