Best Python code snippet using pytest-benchmark
pep418.py
Source:pep418.py  
...348_perf_counter.use_monotonic = has_monotonic349def perf_counter():350    return _perf_counter(False)[0]351if os.name == 'nt':352    def _process_time(use_info):353        handle = GetCurrentProcess()354        process_times = GetProcessTimes(handle)355        value = (process_times[2] + process_times[3]) * 1e-7356        if use_info:357            info = {358                "implementation": "GetProcessTimes()",359                "resolution": 1e-7,360                "monotonic": True,361                "adjustable": False,362                # FIXME: call GetSystemTimeAdjustment() to get the resolution363            }364        else:365            info = None366        return (value, info)367else:368    import os369    try:370        import resource371    except ImportError:372        has_resource = False373    else:374        has_resource = True375    def _process_time(use_info):376        info = None377        if _process_time.clock_id is not None:378            try:379                return _clock_gettime_info(use_info, _process_time.clock_id)380            except OSError:381                _process_time.clock_id = None382        if _process_time.use_getrusage:383            try:384                usage = resource.getrusage(resource.RUSAGE_SELF)385                value = usage[0] + usage[1]386            except OSError:387                _process_time.use_getrusage = False388            else:389                if use_info:390                    info = {391                        "implementation": "getrusage(RUSAGE_SELF)",392                        "resolution": 1e-6,393                        "monotonic": True,394                        "adjustable": False,395                    }396                return (value, info)397        if _process_time.use_times:398            try:399                times = os.times()400                value = times[0] + times[1]401            except OSError:402                _process_time.use_getrusage = False403            else:404                if use_info:405                    try:406                        ticks_per_second = os.sysconf("SC_CLK_TCK")407                    except ValueError:408                        ticks_per_second = 60 # FIXME: get HZ constant409                    info = {410                        "implementation": "times()",411                        "resolution": 1.0 / ticks_per_second,412                        "monotonic": True,413                        "adjustable": False,414                    }415                return (value, info)416        return _libc_clock_info(use_info)417    if has_clock_gettime and CLOCK_PROCESS_CPUTIME_ID is not None:418        _process_time.clock_id = CLOCK_PROCESS_CPUTIME_ID419    elif has_clock_gettime and CLOCK_PROF is not None:420        _process_time.clock_id = CLOCK_PROF421    else:422        _process_time.clock_id = None423    _process_time.use_getrusage = has_resource424    # On OS/2, only the 5th field of os.times() is set, others are zeros425    _process_time.use_times = (hasattr(os, 'times') and os.name != 'os2')426def process_time():427    return _process_time(False)[0]428if os.name == "nt":429    def _time(use_info):430        value = GetSystemTimeAsFileTime() * 1e-7431        if use_info:432            info = {433                'implementation': 'GetSystemTimeAsFileTime',434                'resolution': 1e-7,435                'monotonic': False,436                # FIXME: call GetSystemTimeAdjustment() to get the resolution437                # and adjustable438            }439        else:440            info = None441        return (value, info)442else:443    def _time(use_info):444        info = None445        if has_clock_gettime and CLOCK_REALTIME is not None:446            try:447                return _clock_gettime_info(use_info, CLOCK_REALTIME)448            except OSError:449                # CLOCK_REALTIME is not supported (unlikely)450                pass451        if has_gettimeofday:452            try:453                tv = gettimeofday()454            except OSError:455                # gettimeofday() should not fail456                pass457            else:458                if use_info:459                    info = {460                        'monotonic': False,461                        "implementation": "gettimeofday()",462                        "resolution": 1e-6,463                        'monotonic': False,464                        'adjustable': True,465                    }466                value = tv.tv_sec + tv.tv_usec * 1e-6467                return (value, info)468        # FIXME: implement ftime()469        if has_ftime:470            if use_info:471                info = {472                    "implementation": "ftime()",473                    "resolution": 1e-3,474                    'monotonic': False,475                    'adjustable': True,476                }477            value = ftime()478        elif has_libc_time:479            if use_info:480                info = {481                    "implementation": "time()",482                    "resolution": 1.0,483                    'monotonic': False,484                    'adjustable': True,485                }486            value = float(_libc_time())487        else:488            if use_info:489                info = {490                    "implementation": "time.time()",491                    'monotonic': False,492                    'adjustable': True,493                }494                if os.name == "nt":495                    # On Windows, time.time() uses ftime()496                    info["resolution"] = 1e-3497                else:498                    # guess that time.time() uses gettimeofday()499                    info["resolution"] = 1e-6500            value = python_time.time()501        return (value, info)502def time():503    return _time(False)[0]504try:505    import select506except ImportError:507    has_select = False508else:509    # FIXME: On Windows, select.select([], [], [], seconds) fails with510    #        select.error(10093)511    has_select = (hasattr(select, "select") and os.name != "nt")512if has_select:513    def _sleep(seconds):514        return select.select([], [], [], seconds)515elif has_delay:516    def _sleep(seconds):517        milliseconds = int(seconds * 1000)518        # FIXME519        delay(milliseconds)520#elif os.name == "nt":521#    def _sleep(seconds):522#        milliseconds = int(seconds * 1000)523#        # FIXME: use ctypes524#        win32api.ResetEvent(hInterruptEvent);525#        win32api.WaitForSingleObject(sleep.sigint_event, milliseconds)526#527#    sleep.sigint_event = win32api.CreateEvent(NULL, TRUE, FALSE, FALSE)528#    # SetEvent(sleep.sigint_event) will be called by the signal handler of SIGINT529elif os.name == "os2":530    def _sleep(seconds):531        milliseconds = int(seconds * 1000)532        # FIXME533        DosSleep(milliseconds)534elif has_libc_sleep:535    def _sleep(seconds):536        seconds = int(seconds)537        _libc_sleep(seconds)538else:539    def _sleep(seconds):540        python_time.sleep(seconds)541def sleep(seconds):542    if seconds < 0:543        raise ValueError("sleep length must be non-negative")544    _sleep(seconds)545def _libc_clock_info(use_info):546    if use_info:547        info = {548            'implementation': 'clock()',549            'resolution': 1.0,550            # FIXME: 'resolution': 1.0 / CLOCKS_PER_SEC,551            'monotonic': True,552            'adjustable': False,553        }554        if os.name != "nt":555            info['monotonic'] = True556    else:557        info = None558    if has_libc_clock:559        value = _libc_clock()560        if use_info:561            info['implementation'] = 'clock()'562    else:563        value = python_time.clock()564        if use_info:565            info['implementation'] = 'time.clock()'566    return (value, info)567def _win_perf_counter(use_info):568    if _win_perf_counter.perf_frequency is None:569        try:570            _win_perf_counter.perf_frequency = float(QueryPerformanceFrequency())571        except WindowsError:572            # QueryPerformanceFrequency() fails if the installed573            # hardware does not support a high-resolution performance574            # counter575            return (None, None)576    value = QueryPerformanceCounter() / _win_perf_counter.perf_frequency577    if use_info:578        info = {579            'implementation': 'QueryPerformanceCounter',580            'resolution': 1.0 / _win_perf_counter.perf_frequency,581            'monotonic': True,582            'adjustable': False,583        }584    else:585        info = None586    return (value, info)587_win_perf_counter.perf_frequency = None588if os.name == 'nt':589    def _clock(use_info):590        info = None591        if _clock.use_performance_counter:592            value, info = _win_perf_counter(use_info)593            if value is not None:594                return (value, info)595        return _libc_clock_info(use_info)596    _clock.use_performance_counter = True597else:598    def _clock(use_info):599        return _libc_clock_info(use_info)600def clock():601    return _clock(False)[0]602class clock_info(object):603    def __init__(self, implementation, monotonic, adjustable, resolution):604        self.implementation = implementation605        self.monotonic = monotonic606        self.adjustable = adjustable607        self.resolution = resolution608    def __repr__(self):609        return (610            'clockinfo(adjustable=%s, implementation=%r, monotonic=%s, resolution=%s'611            % (self.adjustable, self.implementation, self.monotonic, self.resolution))612def get_clock_info(name):613    if name == 'clock':614        info = _clock(True)[1]615    elif name == 'perf_counter':616        info = _perf_counter(True)[1]617    elif name == 'process_time':618        info = _process_time(True)[1]619    elif name == 'time':620        info = _time(True)[1]621    elif has_monotonic and name == 'monotonic':622        info = _monotonic(True)[1]623    else:624        raise ValueError("unknown clock: %s" % name)625    return clock_info(**info)626if __name__ == "__main__":627    import threading628    import unittest629    from errno import EPERM630    class TestPEP418(unittest.TestCase):631        if not hasattr(unittest.TestCase, 'assertIsInstance'):632            # Python < 2.7 or Python < 3.2633            def assertIsInstance(self, obj, klass):634                self.assertTrue(isinstance(obj, klass))635            def assertGreater(self, a, b):636                self.assertTrue(a > b)637            def assertLess(self, a, b):638                self.assertTrue(a < b)639            def assertLessEqual(self, a, b):640                self.assertTrue(a <= b)641            def assertAlmostEqual(self, first, second, delta):642                self.assertTrue(abs(first - second) <= delta)643        def test_clock(self):644            clock()645            info = get_clock_info('clock')646            self.assertEqual(info.monotonic, True)647            self.assertEqual(info.adjustable, False)648        def test_get_clock_info(self):649            clocks = ['clock', 'perf_counter', 'process_time', 'time']650            if has_monotonic:651                clocks.append('monotonic')652            for name in clocks:653                info = get_clock_info(name)654                self.assertIsInstance(info.implementation, str)655                self.assertNotEqual(info.implementation, '')656                self.assertIsInstance(info.monotonic, bool)657                self.assertIsInstance(info.resolution, float)658                # 0 < resolution <= 1.0659                self.assertGreater(info.resolution, 0)660                self.assertLessEqual(info.resolution, 1)661                self.assertIsInstance(info.adjustable, bool)662            self.assertRaises(ValueError, get_clock_info, 'xxx')663        if not has_monotonic:664            print("Skip test_monotonic: need time.monotonic")665        else:666            def test_monotonic(self):667                t1 = monotonic()668                python_time.sleep(0.1)669                t2 = monotonic()670                dt = t2 - t1671                self.assertGreater(t2, t1)672                self.assertAlmostEqual(dt, 0.1, delta=0.2)673                info = get_clock_info('monotonic')674                self.assertEqual(info.monotonic, True)675                self.assertEqual(info.adjustable, False)676        if not has_monotonic or not has_clock_gettime:677            if not has_monotonic:678                print('Skip test_monotonic_settime: need time.monotonic')679            elif not has_clock_gettime:680                print('Skip test_monotonic_settime: need time.clock_settime')681        else:682            def test_monotonic_settime(self):683                t1 = monotonic()684                realtime = clock_gettime(CLOCK_REALTIME)685                # jump backward with an offset of 1 hour686                try:687                    clock_settime(CLOCK_REALTIME, realtime - 3600)688                except OSError as err:689                    if err.errno == EPERM:690                        if hasattr(unittest, 'SkipTest'):691                            raise unittest.SkipTest(str(err))692                        else:693                            print("Skip test_monotonic_settime: %s" % err)694                            return695                    else:696                        raise697                t2 = monotonic()698                clock_settime(CLOCK_REALTIME, realtime)699                # monotonic must not be affected by system clock updates700                self.assertGreaterEqual(t2, t1)701        def test_perf_counter(self):702            perf_counter()703        def test_process_time(self):704            start = process_time()705            python_time.sleep(0.1)706            stop = process_time()707            self.assertLess(stop - start, 0.01)708            info = get_clock_info('process_time')709            self.assertEqual(info.monotonic, True)710            self.assertEqual(info.adjustable, False)711        def test_process_time_threads(self):712            class BusyThread(threading.Thread):713                def run(self):714                    while not self.stop:715                        pass716            thread = BusyThread()717            thread.stop = False...test_link_hook.py
Source:test_link_hook.py  
...15        self.forward_preprocess_args = []16        self.forward_postprocess_args = []17    def added(self, link):18        assert link is None or isinstance(link, chainer.Link)19        self.added_args.append((_process_time(), link))20    def deleted(self, link):21        assert link is None or isinstance(link, chainer.Link)22        self.deleted_args.append((_process_time(), link))23    def forward_preprocess(self, args):24        assert isinstance(args.link, chainer.Link)25        assert isinstance(args.forward_name, str)26        assert isinstance(args.args, tuple)27        assert isinstance(args.kwargs, dict)28        assert isinstance(str(args), str)29        assert isinstance(repr(args), str)30        self.forward_preprocess_args.append((_process_time(), args))31    def forward_postprocess(self, args):32        assert isinstance(args.link, chainer.Link)33        assert isinstance(args.forward_name, str)34        assert isinstance(args.args, tuple)35        assert isinstance(args.kwargs, dict)36        assert hasattr(args, 'out')37        assert isinstance(str(args), str)38        assert isinstance(repr(args), str)39        self.forward_postprocess_args.append((_process_time(), args))40class MyModel(chainer.Chain):41    def __init__(self, w):42        super(MyModel, self).__init__()43        with self.init_scope():44            self.l1 = chainer.links.Linear(3, 2, initialW=w)45    def forward(self, x, test1, test2):46        return self.l1(x)47class TestLinkHook(unittest.TestCase):48    def _create_model_and_data(self):49        x = numpy.array([[3, 1, 2]], numpy.float32)50        w = numpy.array([[1, 3, 2], [6, 4, 5]], numpy.float32)51        dot = numpy.dot(x, w.T)52        model = MyModel(w)53        return model, x, dot...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
