Python timeit.timeit() Examples

The following are 30 code examples for showing how to use timeit.timeit(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module timeit , or try the search function .

Example 1
Project: asn1tools   Author: eerimoq   File: ber.py    License: MIT License 6 votes vote down vote up
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 
Example 2
Project: asn1tools   Author: eerimoq   File: ber.py    License: MIT License 6 votes vote down vote up
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 
Example 3
Project: asn1tools   Author: eerimoq   File: compile_methods.py    License: MIT License 6 votes vote down vote up
def method_compile_file():
    print("Parsing and compiling '{}' from file... ".format(RRC_8_6_0_ASN_PATH),
          end='',
          flush=True)

    def compile_file():
        asn1tools.compile_files(RRC_8_6_0_ASN_PATH)

    time = timeit.timeit(compile_file, number=ITERATIONS)

    print('done.')

    with open(RRC_8_6_0_ASN_PATH, 'rb') as fin:
        string = fin.read()

    return round(time, 5), len(string) 
Example 4
Project: asn1tools   Author: eerimoq   File: compile_methods.py    License: MIT License 6 votes vote down vote up
def method_compile_string():
    with open(RRC_8_6_0_ASN_PATH, 'r') as fin:
        string = fin.read()

    print("Parsing and compiling '{}'... ".format(RRC_8_6_0_ASN_PATH),
          end='',
          flush=True)

    def compile_string():
        asn1tools.compile_string(string)

    time = timeit.timeit(compile_string, number=ITERATIONS)

    print('done.')

    return round(time, 5), len(string) 
Example 5
Project: restrain-jit   Author: thautwarm   File: test_array_op.py    License: MIT License 6 votes vote down vote up
def test_repeat_append_nojit():
    x = []
    for i in range(100000):
        x.append(i)
    return x


# print(test_repeat_append_jit())

# print(test_repeat_append_jit_foreach())
#
# for e in (test_repeat_append_jit_foreach.__func_info__.r_codeinfo.instrs):
#     print(e)
# show_instrs(test_repeat_append_jit_foreach.__func_info__.r_codeinfo.instrs)
#
# %timeit test_repeat_append_jit()
# %timeit test_repeat_append_nojit()
# %timeit test_repeat_append_jit_foreach() 
Example 6
Project: fcsparser   Author: eyurtsev   File: test_fcs_reader.py    License: MIT License 6 votes vote down vote up
def test_speed_of_reading_fcs_files(self):
        """Test the speed of loading a FCS files"""
        file_path = FILE_IDENTIFIER_TO_PATH['mq fcs 3.1']
        number = 1000

        time = timeit.timeit(
            lambda: parse_fcs(file_path, meta_data_only=True, reformat_meta=False), number=number)

        print('Loading fcs file {0} times with meta_data only without reformatting of '
              'meta takes {1} per loop'.format(time / number, number))

        time = timeit.timeit(
            lambda: parse_fcs(file_path, meta_data_only=True, reformat_meta=True), number=number)
        print('Loading fcs file {0} times with meta_data only with reformatting of '
              'meta takes {1} per loop'.format(time / number, number))

        time = timeit.timeit(
            lambda: parse_fcs(file_path, meta_data_only=False, reformat_meta=False), number=number)

        print('Loading fcs file {0} times both meta and data but without reformatting of '
              'meta takes {1} per loop'.format(time / number, number)) 
Example 7
Project: python-tabulate   Author: gregbanks   File: benchmark.py    License: MIT License 6 votes vote down vote up
def benchmark(n):
    global methods
    if '--onlyself' in sys.argv[1:]:
        methods = [ m for m in methods if m[0].startswith("tabulate") ]
    else:
        methods = methods

    results = [(desc, timeit(code, setup_code, number=n)/n * 1e6)
               for desc, code in methods]
    mintime = min(map(lambda x: x[1], results))
    results = [(desc, t, t/mintime) for desc, t in
               sorted(results, key=lambda x: x[1])]
    table = tabulate.tabulate(results,
                              [u"Table formatter", u"time, μs", u"rel. time"],
                              u"rst", floatfmt=".1f")
    print codecs.encode(table, "utf-8") 
Example 8
Project: ironpython2   Author: IronLanguages   File: test_timeit.py    License: Apache License 2.0 6 votes vote down vote up
def timeit(self, stmt, setup, number=None):
        self.fake_timer = FakeTimer()
        t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer)
        kwargs = {}
        if number is None:
            number = DEFAULT_NUMBER
        else:
            kwargs['number'] = number
        delta_time = t.timeit(**kwargs)
        self.assertEqual(self.fake_timer.setup_calls, 1)
        self.assertEqual(self.fake_timer.count, number)
        self.assertEqual(delta_time, number)

    # Takes too long to run in debug build.
    #def test_timeit_default_iters(self):
    #    self.timeit(self.fake_stmt, self.fake_setup) 
Example 9
Project: ironpython2   Author: IronLanguages   File: test_timeit.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 10
Project: aumfor   Author: virtualrealitysystems   File: scanprof.py    License: GNU General Public License v3.0 6 votes vote down vote up
def permscan(self, address_space, offset = 0, maxlen = None):
    times = []
    # Run a warm-up scan to ensure the file is cached as much as possible
    self.oldscan(address_space, offset, maxlen)

    perms = list(itertools.permutations(self.checks))
    for i in range(len(perms)):
        self.checks = perms[i]
        print "Running scan {0}/{1}...".format(i + 1, len(perms))
        profobj = ScanProfInstance(self.oldscan, address_space, offset, maxlen)
        value = timeit.timeit(profobj, number = self.repeats)
        times.append((value, len(list(profobj.results)), i))

    print "Scan results"
    print "{0:20} | {1:7} | {2:6} | {3}".format("Time", "Results", "Perm #", "Ordering")
    for val, l, ordering in sorted(times):
        print "{0:20} | {1:7} | {2:6} | {3}".format(val, l, ordering, perms[ordering])
    sys.exit(1) 
Example 11
Project: flask-security   Author: Flask-Middleware   File: test_common.py    License: MIT License 6 votes vote down vote up
def test_auth_token_speed(app, client_nc):
    # To run with old algorithm you have to comment out fs_uniquifier check in UserMixin
    import timeit

    response = json_authenticate(client_nc)
    token = response.json["response"]["user"]["authentication_token"]

    def time_get():
        rp = client_nc.get(
            "/login",
            data={},
            headers={"Content-Type": "application/json", "Authentication-Token": token},
        )
        assert rp.status_code == 200

    t = timeit.timeit(time_get, number=50)
    print("Time for 50 iterations: ", t) 
Example 12
Project: psutil   Author: giampaolo   File: bench_oneshot.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    print("%s methods involved on platform %r (%s iterations, psutil %s):" % (
        len(names), sys.platform, ITERATIONS, psutil.__version__))
    for name in sorted(names):
        print("    " + name)

    # "normal" run
    elapsed1 = timeit.timeit(
        "call_normal(funs)", setup=setup, number=ITERATIONS)
    print("normal:  %.3f secs" % elapsed1)

    # "one shot" run
    elapsed2 = timeit.timeit(
        "call_oneshot(funs)", setup=setup, number=ITERATIONS)
    print("onshot:  %.3f secs" % elapsed2)

    # done
    if elapsed2 < elapsed1:
        print("speedup: +%.2fx" % (elapsed1 / elapsed2))
    elif elapsed2 > elapsed1:
        print("slowdown: -%.2fx" % (elapsed2 / elapsed1))
    else:
        print("same speed") 
Example 13
Project: FlexTensor   Author: KnowingNothing   File: opt_conv_cpu.py    License: MIT License 6 votes vote down vote up
def pytorch_baseliine(batch_size, height, width, channel, kernel_size, output_channel, stride, padding, number=100):
    # conv = torch.nn.Conv2d(channel, output_channel, (kernel_size, kernel_size), (stride, stride), (padding, padding), bias=False)
    # conv = torch.nn.functional.conv2d
    # A = torch.rand([batch_size, channel, height, width])
    # W = torch.rand([output_channel, channel, kernel_size, kernel_size])
    # # warm-up
    # conv(A, W)
    # beg = time.time()
    # for i in range(number):
    #     conv(A, W)
    # end = time.time()

    run_time = timeit.timeit(setup= 'import torch\n'
                                    'conv = torch.nn.functional.conv2d\n'
                                    'A = torch.rand([' + str(batch_size) + ', ' + str(channel) + ', ' + str(height) + ', ' + str(width) + '])\n'
                                    'W = torch.rand([' + str(output_channel) + ', ' + str(channel) + ', ' + str(kernel_size) + ', ' + str(kernel_size) + '])\n'
                                    'conv(A, W)\n',
                               stmt='conv(A, W)',
                               number=number)
    print("pytorch use {}ms".format(run_time / number * 1e3)) 
Example 14
Project: asn1tools   Author: eerimoq   File: uper.py    License: MIT License 5 votes vote down vote up
def asn1tools_encode_decode():
    rrc = asn1tools.compile_files(RRC_8_6_0_ASN_PATH, 'uper')

    def encode():
        rrc.encode('BCCH-DL-SCH-Message',
                   DECODED_MESSAGE_ASN1TOOLS,
                   check_types=False)

    def decode():
        rrc.decode('BCCH-DL-SCH-Message', ENCODED_MESSAGE)

    encode_time = timeit.timeit(encode, number=ITERATIONS)
    decode_time = timeit.timeit(decode, number=ITERATIONS)

    return encode_time, decode_time 
Example 15
Project: asn1tools   Author: eerimoq   File: uper.py    License: MIT License 5 votes vote down vote up
def pycrate_encode_decode():
    try:
        import rrc_8_6_0_pycrate

        rrc = rrc_8_6_0_pycrate.EUTRA_RRC_Definitions.BCCH_DL_SCH_Message
        rrc._SAFE_INIT = False
        rrc._SAFE_VAL = False
        rrc._SAFE_BND = False
        rrc._SAFE_BNDTAB = False

        def encode():
            rrc.set_val(DECODED_MESSAGE_PYCRATE)
            rrc.to_uper()

        def decode():
            rrc.from_uper(ENCODED_MESSAGE)
            rrc()

        encode_time = timeit.timeit(encode, number=ITERATIONS)
        decode_time = timeit.timeit(decode, number=ITERATIONS)
    except ImportError:
        encode_time = float('inf')
        decode_time = float('inf')
        print('Unable to import pycrate.')
    except Exception as e:
        encode_time = float('inf')
        decode_time = float('inf')
        print('pycrate error: {}'.format(str(e)))

    return encode_time, decode_time 
Example 16
Project: asn1tools   Author: eerimoq   File: ber.py    License: MIT License 5 votes vote down vote up
def asn1tools_encode_decode():
    snmp_v1 = asn1tools.compile_files(SNMP_V1_ASN_PATHS)

    def encode():
        snmp_v1.encode('Message',
                       DECODED_MESSAGE_ASN1TOOLS,
                       check_types=False)

    def decode():
        snmp_v1.decode('Message', ENCODED_MESSAGE)

    encode_time = timeit.timeit(encode, number=ITERATIONS)
    decode_time = timeit.timeit(decode, number=ITERATIONS)

    return encode_time, decode_time 
Example 17
Project: asn1tools   Author: eerimoq   File: compile_methods.py    License: MIT License 5 votes vote down vote up
def method_compile_cached_file():
    print("Using cached compilation... ",
          end='',
          flush=True)

    asn1tools.compile_files(RRC_8_6_0_ASN_PATH, cache_dir=CACHE_DIR)

    def compile_file():
        asn1tools.compile_files(RRC_8_6_0_ASN_PATH, cache_dir=CACHE_DIR)

    time = timeit.timeit(compile_file, number=ITERATIONS)

    print('done.')

    def dir_size(path):
        total = 0

        for entry in os.scandir(path):
            if entry.is_file():
                total += entry.stat().st_size
            elif entry.is_dir():
                total += dir_size(entry.path)

        return total

    return round(time, 5), dir_size(CACHE_DIR) 
Example 18
Project: asn1tools   Author: eerimoq   File: compile_methods.py    License: MIT License 5 votes vote down vote up
def method_compile_dict():
    dictionary = asn1tools.parse_files(RRC_8_6_0_ASN_PATH)

    print("Compiling RRC_8_6_0 dictionary... ",
          end='',
          flush=True)

    def compile_dict():
        asn1tools.compile_dict(dictionary)

    time = timeit.timeit(compile_dict, number=ITERATIONS)

    print('done.')

    return round(time, 5), len(str(dictionary)) 
Example 19
Project: asn1tools   Author: eerimoq   File: compile_methods.py    License: MIT License 5 votes vote down vote up
def method_unpickle():
    pickled = pickle.dumps(asn1tools.compile_files(RRC_8_6_0_ASN_PATH))

    print("Unpickling compiled object... ",
          end='',
          flush=True)

    def unpickle():
        pickle.loads(pickled)

    time = timeit.timeit(unpickle, number=ITERATIONS)

    print('done.')

    return round(time, 5), len(pickled) 
Example 20
Project: asn1tools   Author: eerimoq   File: test_ber.py    License: MIT License 5 votes vote down vote up
def test_performance(self):
        cmplx = asn1tools.compile_files('tests/files/complex.asn')

        decoded = {
            'boolean': True,
            'integer': -7,
            'bit-string': (b'\x80', 3),
            'octet-string': b'\x31\x32',
            'null': None,
            'object-identifier': '1.3.2',
            'enumerated': 'one',
            'sequence': {},
            'ia5-string': 'foo'
        }

        encoded = (
            b'\x30\x1e\x01\x01\xff\x02\x01\xf9\x03\x02\x05\x80\x04\x02\x31\x32'
            b'\x05\x00\x06\x02\x2b\x02\x0a\x01\x01\x30\x00\x16\x03\x66\x6f\x6f'
        )

        def encode():
            cmplx.encode('AllUniversalTypes', decoded)

        def decode():
            cmplx.decode('AllUniversalTypes', encoded)

        iterations = 1000

        res = timeit.timeit(encode, number=iterations)
        ms_per_call = 1000 * res / iterations
        print('{} ms per encode call.'.format(round(ms_per_call, 3)))

        res = timeit.timeit(decode, number=iterations)
        ms_per_call = 1000 * res / iterations
        print('{} ms per decode call.'.format(round(ms_per_call, 3))) 
Example 21
Project: restrain-jit   Author: thautwarm   File: test_if.py    License: MIT License 5 votes vote down vote up
def test(f):
    t = timeit(template, number=10_000_000, globals=dict(f=f))
    print(f, 'costs', t) 
Example 22
Project: restrain-jit   Author: thautwarm   File: test_loop.py    License: MIT License 5 votes vote down vote up
def test(f):
    t = timeit(template, number=30000, globals=dict(f=f, seq=[*range(1000)]))
    print(f, 'costs', t) 
Example 23
Project: restrain-jit   Author: thautwarm   File: test_loop.py    License: MIT License 5 votes vote down vote up
def test(f):
    t = timeit(template, number=30000, globals=dict(f=f, seq=[*range(1000)]))
    print(f, 'costs', t) 
Example 24
Project: restrain-jit   Author: thautwarm   File: design2_proof_of_concepts.py    License: MIT License 5 votes vote down vote up
def test(f):
    t = timeit(template, number=10_000_000, globals=dict(f=f))
    print(f, 'costs', t) 
Example 25
Project: restrain-jit   Author: thautwarm   File: one_func_one_class.py    License: MIT License 5 votes vote down vote up
def test(f):
    t = timeit(template, number=10_000_000, globals=dict(f=f))
    print(f, 'costs', t) 
Example 26
Project: ASPP-2018-numpy   Author: ASPP   File: tools.py    License: MIT License 5 votes vote down vote up
def timeit(stmt, globals=globals()):
    import numpy as np
    import timeit as _timeit

    print("Timing '{0}'".format(stmt))
        
    # Rough approximation of a 10 runs
    trial = _timeit.timeit(stmt, globals=globals, number=10)/10
    
    # Maximum duration
    duration = 5.0
    
    # Number of repeat
    repeat = 7
    
    # Compute rounded number of trials
    number = max(1,int(10**np.ceil(np.log((duration/repeat)/trial)/np.log(10))))
    
    # Only report best run
    times = _timeit.repeat(stmt, globals=globals, number=number, repeat=repeat)
    times = np.array(times)/number
    mean = np.mean(times)
    std = np.std(times)

    # Display results
    units = {"s":  1, "ms": 1e-3, "us": 1e-6, "ns": 1e-9}
    for key,value in units.items():
        unit, factor = key, 1/value
        if mean > value: break
    mean *= factor
    std *= factor

    print("%.3g %s ± %.3g %s per loop (mean ± std. dev. of %d runs, %d loops each)" %
          (mean, unit, std, unit, repeat, number)) 
Example 27
Project: python-tabulate   Author: astanin   File: benchmark.py    License: MIT License 5 votes vote down vote up
def benchmark(n):
    global methods
    if "--onlyself" in sys.argv[1:]:
        methods = [m for m in methods if m[0].startswith("tabulate")]
    else:
        methods = methods

    results = [
        (desc, timeit(code, setup_code, number=n) / n * 1e6) for desc, code in methods
    ]
    mintime = min(map(lambda x: x[1], results))
    results = [
        (desc, t, t / mintime) for desc, t in sorted(results, key=lambda x: x[1])
    ]
    table = tabulate.tabulate(
        results, ["Table formatter", "time, μs", "rel. time"], "rst", floatfmt=".1f"
    )

    import platform

    if platform.platform().startswith("Windows"):
        print(table)
    elif python_version_tuple()[0] < "3":
        print(codecs.encode(table, "utf-8"))
    else:
        print(table) 
Example 28
Project: ironpython2   Author: IronLanguages   File: test_timeit.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 29
Project: ironpython2   Author: IronLanguages   File: test_timeit.py    License: Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        try:
            del timeit._fake_timer
        except AttributeError:
            pass 
Example 30
Project: ironpython2   Author: IronLanguages   File: test_timeit.py    License: Apache License 2.0 5 votes vote down vote up
def test_reindent_empty(self):
        self.assertEqual(timeit.reindent("", 0), "")
        self.assertEqual(timeit.reindent("", 4), "")