コード例 #1
0
ファイル: monotonic_clock.py プロジェクト: rfinnie/2ping
    def __init__(self):
        # Unix + CLOCK_MONOTONIC_RAW
        if hasattr(time, 'clock_gettime') and hasattr(time, 'CLOCK_MONOTONIC_RAW'):
            self.info = time.get_clock_info('monotonic')
            self.info.implementation = 'clock_gettime(CLOCK_MONOTONIC_RAW)'

            def _clock():
                return time.clock_gettime(time.CLOCK_MONOTONIC_RAW)

            self.clock = _clock
            self.clock()
            return

        # All other platforms
        for mode in ('perf_counter', 'monotonic', 'clock'):
            try:
                self.info = time.get_clock_info(mode)
            except ValueError:
                continue
            if not self.info.monotonic:
                continue
            if self.info.resolution > 1e-06:
                continue
            self.clock = getattr(time, mode)
            self.clock()
            return

        raise NotImplementedError()
コード例 #2
0
ファイル: test_time.py プロジェクト: ziaridoy20/cpython
    def test_process_time(self):
        # process_time() should not include time spend during a sleep
        start = time.process_time()
        time.sleep(0.100)
        stop = time.process_time()
        # use 20 ms because process_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        # bpo-33723: A busy loop of 100 ms should increase process_time()
        # by at least 15 ms
        min_time = 0.015
        busy_time = 0.100

        # process_time() should include CPU time spent in any thread
        start = time.process_time()
        busy_wait(busy_time)
        stop = time.process_time()
        self.assertGreaterEqual(stop - start, min_time)

        t = threading.Thread(target=busy_wait, args=(busy_time,))
        start = time.process_time()
        t.start()
        t.join()
        stop = time.process_time()
        self.assertGreaterEqual(stop - start, min_time)

        info = time.get_clock_info('process_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #3
0
ファイル: py_02_timeClockTime.py プロジェクト: wellqin/USTC
def time_get_clock_info():
    """Implementation details for the clocks vary by platform
    """
    available_clocks = [
        # ('clock', time.clock), # time.clock is deprecated ..
        ('monotonic', time.monotonic),
        ('perf_counter', time.perf_counter),
        ('process_time', time.process_time),
        ('time', time.time),
    ]
    # i confirmed difference between winos64 and macos in the book 
    
    for clock_name, func in available_clocks:
        print(textwrap.dedent('''\
        {name}:
            adjustable      : {info.adjustable}
            implementations : {info.implementation}
            monotonic       : {info.monotonic}
            resolution      : {info.resolution}
            current         : {current}
        ''').format(
            name=clock_name,
            info=time.get_clock_info(clock_name),
            current=func())      
        )
コード例 #4
0
async def test_current_time():
    t1 = _core.current_time()
    # Windows clock is pretty low-resolution -- appveyor tests fail unless we
    # sleep for a bit here.
    time.sleep(time.get_clock_info("monotonic").resolution)
    t2 = _core.current_time()
    assert t1 < t2
コード例 #5
0
def time_perfcounter_correlation() -> Tuple[float, float]:
    """Get the `perf_counter` value nearest to when time.time() is updated

    Computed if the default timer used by `time.time` on this platform has a resolution
    higher than 10μs, otherwise the current time and perf_counter is directly returned.
    This was chosen as typical timer resolution on Linux/macOS is ~1μs, and the Windows
    platform can vary from ~500μs to 10ms.

    Note this value is based on when `time.time()` is observed to update from Python,
    it is not directly returned by the operating system.

    :returns:
        (t, performance_counter) time.time value and time.perf_counter value when the time.time
        is updated

    """

    # use this if the resolution is higher than 10us
    if get_clock_info("time").resolution > 1e-5:
        t0 = time()
        while True:
            t1, performance_counter = time(), perf_counter()
            if t1 != t0:
                break
    else:
        return time(), perf_counter()
    return t1, performance_counter
コード例 #6
0
    def test_monoclock(self):
        a = tf.monoclock()
        b = tf.monoclock()
        self.assertLessEqual(a, b)
        # print(tf.monoclock())
        # monoclock() should not go backward
        times = [tf.monoclock() for n in range(100)]
        t1 = times[0]
        for t2 in times[1:]:
            self.assertGreaterEqual(t2, t1, "times=%s" % times)
            t1 = t2

        # monoclock() includes time elapsed during a sleep
        t1 = tf.monoclock()
        time.sleep(0.5)
        t2 = tf.monoclock()
        dt = t2 - t1
        self.assertGreater(t2, t1)
        # Issue #20101: On some Windows machines, dt may be slightly low
        self.assertTrue(0.45 <= dt <= 1.0, dt)

        # monoclock() is a monotonic but non adjustable clock
        info = time.get_clock_info('monotonic')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #7
0
ファイル: pythoninfo.py プロジェクト: stackless-dev/stackless
def collect_time(info_add):
    import time

    info_add('time.time', time.time())

    attributes = (
        'altzone',
        'daylight',
        'timezone',
        'tzname',
    )
    copy_attributes(info_add, time, 'time.%s', attributes)

    if hasattr(time, 'get_clock_info'):
        for clock in ('clock', 'monotonic', 'perf_counter',
                      'process_time', 'thread_time', 'time'):
            try:
                # prevent DeprecatingWarning on get_clock_info('clock')
                with warnings.catch_warnings(record=True):
                    clock_info = time.get_clock_info(clock)
            except ValueError:
                # missing clock like time.thread_time()
                pass
            else:
                info_add('time.get_clock_info(%s)' % clock, clock_info)
コード例 #8
0
ファイル: test_time.py プロジェクト: 1st1/cpython
    def test_thread_time(self):
        if not hasattr(time, 'thread_time'):
            if sys.platform.startswith(('linux', 'win')):
                self.fail("time.thread_time() should be available on %r"
                          % (sys.platform,))
            else:
                self.skipTest("need time.thread_time")

        # thread_time() should not include time spend during a sleep
        start = time.thread_time()
        time.sleep(0.100)
        stop = time.thread_time()
        # use 20 ms because thread_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        # thread_time() should include CPU time spent in current thread...
        start = time.thread_time()
        busy_wait(0.100)
        stop = time.thread_time()
        self.assertGreaterEqual(stop - start, 0.020)  # machine busy?

        # ...but not in other threads
        t = threading.Thread(target=busy_wait, args=(0.100,))
        start = time.thread_time()
        t.start()
        t.join()
        stop = time.thread_time()
        self.assertLess(stop - start, 0.020)

        info = time.get_clock_info('thread_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #9
0
ファイル: test_time.py プロジェクト: yewsGitHub/cpython
    def test_process_time(self):
        # process_time() should not include time spend during a sleep
        start = time.process_time()
        time.sleep(0.100)
        stop = time.process_time()
        # use 20 ms because process_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        # process_time() should include CPU time spent in any thread
        start = time.process_time()
        busy_wait(0.100)
        stop = time.process_time()
        self.assertGreaterEqual(stop - start, 0.020)  # machine busy?

        t = threading.Thread(target=busy_wait, args=(0.100, ))
        start = time.process_time()
        t.start()
        t.join()
        stop = time.process_time()
        self.assertGreaterEqual(stop - start, 0.020)  # machine busy?

        info = time.get_clock_info('process_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #10
0
ファイル: test_time.py プロジェクト: 1st1/cpython
    def test_process_time(self):
        # process_time() should not include time spend during a sleep
        start = time.process_time()
        time.sleep(0.100)
        stop = time.process_time()
        # use 20 ms because process_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        # process_time() should include CPU time spent in any thread
        start = time.process_time()
        busy_wait(0.100)
        stop = time.process_time()
        self.assertGreaterEqual(stop - start, 0.020)  # machine busy?

        t = threading.Thread(target=busy_wait, args=(0.100,))
        start = time.process_time()
        t.start()
        t.join()
        stop = time.process_time()
        self.assertGreaterEqual(stop - start, 0.020)  # machine busy?

        info = time.get_clock_info('process_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #11
0
ファイル: test_time.py プロジェクト: Apoorvadabhere/cpython
    def test_process_time(self):
        # process_time() should not include time spend during a sleep
        start = time.process_time()
        time.sleep(0.100)
        stop = time.process_time()
        # use 20 ms because process_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        # bpo-33723: A busy loop of 100 ms should increase process_time()
        # by at least 15 ms
        min_time = 0.015
        busy_time = 0.100

        # process_time() should include CPU time spent in any thread
        start = time.process_time()
        busy_wait(busy_time)
        stop = time.process_time()
        self.assertGreaterEqual(stop - start, min_time)

        t = threading.Thread(target=busy_wait, args=(busy_time,))
        start = time.process_time()
        t.start()
        t.join()
        stop = time.process_time()
        self.assertGreaterEqual(stop - start, min_time)

        info = time.get_clock_info('process_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #12
0
ファイル: base_events.py プロジェクト: tclh123/cpython
 def __init__(self):
     self._ready = collections.deque()
     self._scheduled = []
     self._default_executor = None
     self._internal_fds = 0
     self._running = False
     self._granularity = time.get_clock_info('monotonic').resolution
コード例 #13
0
def analyse_time(size_to_test, no_of_trials):
    """This function takes list of array and number of trials as argument. It prints time taken to perfrom giftwrap algorithm for given lists"""
    
    if sys.version_info < (3, 3):
        get_time = time.clock
    else:
        get_time = time.perf_counter
        REZ = time.get_clock_info('perf_counter').resolution   

    total_time = 0  
    for trial in range(no_of_trials):
        list_to_test = generate_random_array(size_to_test)
        start = get_time()
        sol = grahamscan_e(list_to_test)
        end = get_time()
        total_time += (end - start)
        
    time_taken_per_locate = (1.0*total_time) / no_of_trials
    print('finish timing for array with {} random points'.format(size_to_test))
    
    #Uncomment if want graph
    #draw_graph(list_to_test, sol)
    
    print(size_to_test)
    print(time_taken_per_locate)
    return time_taken_per_locate
コード例 #14
0
ファイル: pythoninfo.py プロジェクト: Eyepea/cpython
def collect_time(info_add):
    import time

    info_add('time.time', time.time())

    attributes = (
        'altzone',
        'daylight',
        'timezone',
        'tzname',
    )
    copy_attributes(info_add, time, 'time.%s', attributes)

    if hasattr(time, 'get_clock_info'):
        for clock in ('clock', 'monotonic', 'perf_counter',
                      'process_time', 'thread_time', 'time'):
            try:
                # prevent DeprecatingWarning on get_clock_info('clock')
                with warnings.catch_warnings(record=True):
                    clock_info = time.get_clock_info(clock)
            except ValueError:
                # missing clock like time.thread_time()
                pass
            else:
                info_add('time.get_clock_info(%s)' % clock, clock_info)
コード例 #15
0
def get_clock_info(clock_name: str) -> 'ClockInfo':
    # Check local structure in case even a standard clock name has been
    # overwritten which is not recommended, but...
    if clock_name in _CLOCKS_INFO_ATTR:
        return ClockInfo(function=CLOCKS[clock_name],
                         **_CLOCKS_INFO_ATTR[clock_name])
    return ClockInfo(function=CLOCKS[clock_name],
                     **vars(std_time.get_clock_info(clock_name)))
コード例 #16
0
def get_clock_info(clock_name):
    # Check local structure in case even a standard clock name has been
    # overwritten.
    if clock_name in _CLOCKS_INFO:
        return ClockInfo(function=CLOCKS[clock_name],
                         **_CLOCKS_INFO[clock_name])
    return ClockInfo(function=CLOCKS[clock_name],
                     **vars(std_time.get_clock_info(clock_name)))
コード例 #17
0
 def test_process_time(self):
     start = time.process_time()
     time.sleep(0.1)
     stop = time.process_time()
     self.assertLess(stop - start, 0.02)
     info = time.get_clock_info('process_time')
     self.assertTrue(info.monotonic)
     self.assertFalse(info.adjustable)
コード例 #18
0
    def test_clock(self):
        with self.assertWarns(DeprecationWarning):
            time.clock()

        with self.assertWarns(DeprecationWarning):
            info = time.get_clock_info('clock')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #19
0
ファイル: test_time.py プロジェクト: 1st1/cpython
    def test_clock(self):
        with self.assertWarns(DeprecationWarning):
            time.clock()

        with self.assertWarns(DeprecationWarning):
            info = time.get_clock_info('clock')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #20
0
ファイル: base_events.py プロジェクト: BrandonOsas/WEB-DEV
 def __init__(self):
     self._ready = collections.deque()
     self._scheduled = []
     self._default_executor = None
     self._internal_fds = 0
     self._running = False
     self._clock_resolution = time.get_clock_info('monotonic').resolution
     self._exception_handler = None
     self._debug = False
コード例 #21
0
ファイル: test_time.py プロジェクト: Naddiseo/cpython
    def test_process_time(self):
        start = time.process_time()
        time.sleep(0.1)
        stop = time.process_time()
        self.assertLess(stop - start, 0.01)

        info = time.get_clock_info('process_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjusted)
    def __init__(self, builder=None):
        """
        :param builder: A
            :class:`systemlink.messagebus.message_subsciber_builder.MessageSubscriberBuilder`
            object used in the construction of this object. May be ``None`` if default
            behavior is desired.
        :type builder:
            systemlink.messagebus.message_subsciber_builder.MessageSubscriberBuilder
        """
        self._closing = False
        self._amqp_connection_manager = builder.connection_manager
        self._amqp_consumers = []
        self._msg_name_callbacks = {}
        self._corr_id_callbacks = {}
        self._sync_callbacks = {}
        self._queue_name = builder.queue_name
        self._explicit_ack = builder.explicit_ack
        self._correlation_id_timeout = builder.correlation_id_timeout
        self._local_message_queue = None
        self._owns_default_binding = False

        if USE_MONOTONIC_CLOCK:
            clock_info = time.get_clock_info('monotonic')  # pylint: disable=no-member
            if clock_info.adjustable:
                self._clock_res = clock_info.resolution
            else:
                self._clock_res = 1
            self._last_correlation_id_check = time.monotonic()  # pylint: disable=no-member
        else:
            self._clock_res = None
            self._last_correlation_id_check = datetime.datetime.utcnow()

        self._callback = builder.callback
        self._trace_unhandled_message = TracePoint('UnhandledMessage')
        self._trace_logger = builder.trace_logger
        if self._trace_logger is not None:
            self._trace_unhandled_message = self._trace_logger.make_trace_point(
                'UnhandledMessage')
        self._message_handling_threads = []
        if builder.local_queue_task_threads > 1:
            self._local_message_queue = Queue(builder.max_local_queue_depth)
            for _ in range(builder.local_queue_task_threads):
                thread = threading.Thread(
                    target=self._process_message_from_local_queue)
                thread.daemon = True
                thread.start()
                self._message_handling_threads.append(thread)
        for _ in range(builder.number_of_amqp_consumers):
            self._amqp_consumers.append(self._create_consumer(builder))
        if builder.register_default_binding:
            params = [self._queue_name, '#']
            self.register_binding(params)
            if builder.is_instance_subscriber:
                self._owns_default_binding = True
        if builder.auto_start_consumers:
            self.start_handling_messages()
コード例 #23
0
ファイル: base_events.py プロジェクト: GoMADAO/Lessa-PLT
 def __init__(self):
     self._closed = False
     self._ready = collections.deque()
     self._scheduled = []
     self._default_executor = None
     self._internal_fds = 0
     self._running = False
     self._clock_resolution = time.get_clock_info('monotonic').resolution
     self._exception_handler = None
     self._debug = False
コード例 #24
0
    def test_monotonic(self):
        t1 = time.monotonic()
        time.sleep(0.1)
        t2 = time.monotonic()
        dt = t2 - t1
        self.assertGreater(t2, t1)
        self.assertAlmostEqual(dt, 0.1, delta=0.2)

        info = time.get_clock_info('monotonic')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #25
0
ファイル: test_time.py プロジェクト: juleskt/ek128_work
    def test_monotonic(self):
        t1 = time.monotonic()
        time.sleep(0.1)
        t2 = time.monotonic()
        dt = t2 - t1
        self.assertGreater(t2, t1)
        self.assertAlmostEqual(dt, 0.1, delta=0.2)

        info = time.get_clock_info("monotonic")
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #26
0
    def test_get_clock_info(self):
        clocks = ['clock', 'monotonic', 'perf_counter', 'process_time', 'time']

        for name in clocks:
            if name == 'clock':
                with self.assertWarns(DeprecationWarning):
                    info = time.get_clock_info('clock')
            else:
                info = time.get_clock_info(name)

            #self.assertIsInstance(info, dict)
            self.assertIsInstance(info.implementation, str)
            self.assertNotEqual(info.implementation, '')
            self.assertIsInstance(info.monotonic, bool)
            self.assertIsInstance(info.resolution, float)
            # 0.0 < resolution <= 1.0
            self.assertGreater(info.resolution, 0.0)
            self.assertLessEqual(info.resolution, 1.0)
            self.assertIsInstance(info.adjustable, bool)

        self.assertRaises(ValueError, time.get_clock_info, 'xxx')
コード例 #27
0
ファイル: test_time.py プロジェクト: 1st1/cpython
    def test_get_clock_info(self):
        clocks = ['clock', 'monotonic', 'perf_counter', 'process_time', 'time']

        for name in clocks:
            if name == 'clock':
                with self.assertWarns(DeprecationWarning):
                    info = time.get_clock_info('clock')
            else:
                info = time.get_clock_info(name)

            #self.assertIsInstance(info, dict)
            self.assertIsInstance(info.implementation, str)
            self.assertNotEqual(info.implementation, '')
            self.assertIsInstance(info.monotonic, bool)
            self.assertIsInstance(info.resolution, float)
            # 0.0 < resolution <= 1.0
            self.assertGreater(info.resolution, 0.0)
            self.assertLessEqual(info.resolution, 1.0)
            self.assertIsInstance(info.adjustable, bool)

        self.assertRaises(ValueError, time.get_clock_info, 'xxx')
コード例 #28
0
ファイル: test_time.py プロジェクト: little-tee/GTC
    def test_process_time(self):
        # process_time() should not include time spend during a sleep
        start = time.process_time()
        time.sleep(0.100)
        stop = time.process_time()
        # use 20 ms because process_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        info = time.get_clock_info('process_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #29
0
ファイル: test_time.py プロジェクト: pykomke/Kurz_Python_KE
    def test_monotonic(self):
        t1 = time.monotonic()
        time.sleep(0.5)
        t2 = time.monotonic()
        dt = t2 - t1
        self.assertGreater(t2, t1)
        # Issue #20101: On some Windows machines, dt may be slightly low
        self.assertTrue(0.45 <= dt <= 1.0, dt)

        info = time.get_clock_info('monotonic')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #30
0
ファイル: test_time.py プロジェクト: 5outh/Databases-Fall2014
    def test_process_time(self):
        # process_time() should not include time spend during a sleep
        start = time.process_time()
        time.sleep(0.100)
        stop = time.process_time()
        # use 20 ms because process_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        info = time.get_clock_info('process_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #31
0
ファイル: base_events.py プロジェクト: kwatch/cpython
 def __init__(self):
     self._closed = False
     self._ready = collections.deque()
     self._scheduled = []
     self._default_executor = None
     self._internal_fds = 0
     self._running = False
     self._clock_resolution = time.get_clock_info('monotonic').resolution
     self._exception_handler = None
     self._debug = (not sys.flags.ignore_environment
                    and bool(os.environ.get('PYTHONASYNCIODEBUG')))
     # In debug mode, if the execution of a callback or a step of a task
     # exceed this duration in seconds, the slow callback/task is logged.
     self.slow_callback_duration = 0.1
コード例 #32
0
 def test_get_clock_info(self):
     clocks = ['clock', 'perf_counter', 'process_time', 'time']
     if hasattr(time, 'monotonic'):
         clocks.append('monotonic')
     for name in clocks:
         info = time.get_clock_info(name)
         self.assertIsInstance(info.implementation, str)
         self.assertNotEqual(info.implementation, '')
         self.assertIsInstance(info.monotonic, bool)
         self.assertIsInstance(info.resolution, float)
         self.assertGreater(info.resolution, 0.0)
         self.assertLessEqual(info.resolution, 1.0)
         self.assertIsInstance(info.adjustable, bool)
     self.assertRaises(ValueError, time.get_clock_info, 'xxx')
コード例 #33
0
ファイル: base_events.py プロジェクト: alex/cpython
 def __init__(self):
     self._closed = False
     self._ready = collections.deque()
     self._scheduled = []
     self._default_executor = None
     self._internal_fds = 0
     self._running = False
     self._clock_resolution = time.get_clock_info('monotonic').resolution
     self._exception_handler = None
     self._debug = (not sys.flags.ignore_environment
                    and bool(os.environ.get('PYTHONASYNCIODEBUG')))
     # In debug mode, if the execution of a callback or a step of a task
     # exceed this duration in seconds, the slow callback/task is logged.
     self.slow_callback_duration = 0.1
コード例 #34
0
ファイル: test_time.py プロジェクト: Naddiseo/cpython
    def test_monotonic(self):
        t1 = time.monotonic()
        time.sleep(0.1)
        t2 = time.monotonic()
        dt = t2 - t1
        self.assertGreater(t2, t1)
        self.assertAlmostEqual(dt, 0.1, delta=0.2)

        info = time.get_clock_info('monotonic')
        self.assertTrue(info.monotonic)
        if sys.platform == 'linux':
            self.assertTrue(info.adjusted)
        else:
            self.assertFalse(info.adjusted)
コード例 #35
0
 def test_get_clock_info(self):
     import time
     clocks = ['clock', 'perf_counter', 'process_time', 'time']
     if hasattr(time, 'monotonic'):
         clocks.append('monotonic')
     for name in clocks:
         info = time.get_clock_info(name)
         assert isinstance(info.implementation, str)
         assert info.implementation != ''
         assert isinstance(info.monotonic, bool)
         assert isinstance(info.resolution, float)
         assert info.resolution > 0.0
         assert info.resolution <= 1.0
         assert isinstance(info.adjustable, bool)
コード例 #36
0
def timeit(measure_func, precision):
    """
    Measure the process time for measure_func with the desired precision, and
    return a tuple(mean_us, stdev_us, num_runs, num_out).
    """

    num_runs = 100  # Number of measurements to eliminate outliers
    min_rep = 5  # Minimum number of repetitions

    res_s = get_clock_info('process_time').resolution

    # Determine number of repetitions needed based on desired precision and
    # given timer resolution
    t1_s = process_time()
    measure_func()
    t2_s = process_time()
    t_s = t2_s - t1_s
    rep = max(int(float(res_s) / t_s / precision), min_rep) \
        if t_s != 0 else min_rep

    # Perform the measurement a number of times and store the results
    results = []
    for _ in six.moves.range(num_runs):
        t1_s = process_time()
        for _j in six.moves.range(rep):  # pylint: disable=unused-variable
            measure_func()
        t2_s = process_time()
        t_us = 1.0E6 * (t2_s - t1_s) / rep
        results.append(t_us)

    # Eliminate upper outliers in the results. Even though we measure process
    # time, it includes any activities done by the Python process outside of
    # our actual measured code.
    mean = statistics.mean(results)
    stdev = statistics.stdev(results)
    cleaned_results = []
    outliers = []
    for x in results:
        if x < mean + 1 * stdev:
            cleaned_results.append(x)
        else:
            outliers.append(x)
    num_out = len(outliers)

    # Calculate mean and standard deviation from cleaned results
    mean_us = statistics.mean(cleaned_results)
    stdev_us = statistics.stdev(cleaned_results)

    return mean_us, stdev_us, num_runs, num_out
コード例 #37
0
ファイル: pythoninfo.py プロジェクト: 1st1/cpython
def collect_time(info_add):
    import time

    attributes = (
        'altzone',
        'daylight',
        'timezone',
        'tzname',
    )
    copy_attributes(info_add, time, 'time.%s', attributes)

    if hasattr(time, 'get_clock_info'):
        for clock in ('time', 'perf_counter'):
            tinfo = time.get_clock_info(clock)
            info_add('time.%s' % clock, tinfo)
コード例 #38
0
 def test_monotonic(self):
     times = [time.monotonic() for n in range(100)]
     t1 = times[0]
     for t2 in times[1:]:
         self.assertGreaterEqual(t2, t1, 'times=%s' % times)
         t1 = t2
     t1 = time.monotonic()
     time.sleep(0.5)
     t2 = time.monotonic()
     dt = t2 - t1
     self.assertGreater(t2, t1)
     self.assertTrue(0.45 <= dt <= 1.0, dt)
     info = time.get_clock_info('monotonic')
     self.assertTrue(info.monotonic)
     self.assertFalse(info.adjustable)
コード例 #39
0
def collect_time(info_add):
    import time

    attributes = (
        'altzone',
        'daylight',
        'timezone',
        'tzname',
    )
    copy_attributes(info_add, time, 'time.%s', attributes)

    if hasattr(time, 'get_clock_info'):
        for clock in ('time', 'perf_counter'):
            tinfo = time.get_clock_info(clock)
            info_add('time.%s' % clock, tinfo)
コード例 #40
0
ファイル: base.py プロジェクト: danielhrisca/pyxcp
    def __init__(self, config=None):
        self.parent = None
        self.config = Configuration(BaseTransport.PARAMETER_MAP or {}, config
                                    or {})
        self.closeEvent = threading.Event()
        loglevel = self.config.get("LOGLEVEL")
        self._debug = loglevel == "DEBUG"

        self.logger = Logger("transport.Base")
        self.logger.setLevel(loglevel)
        self.counterSend = 0
        self.counterReceived = -1
        create_daq_timestamps = self.config.get("CREATE_DAQ_TIMESTAMPS")
        self.create_daq_timestamps = False if create_daq_timestamps is None else create_daq_timestamps
        timeout = self.config.get("TIMEOUT")
        self.alignment = self.config.get("ALIGNMENT")
        self.timeout = 2.0 if timeout is None else timeout
        self.timer_restart_event = threading.Event()
        self.timing = Timing()
        self.resQueue = deque()
        self.daqQueue = deque()
        self.evQueue = deque()
        self.servQueue = deque()
        self.listener = threading.Thread(
            target=self.listen,
            args=(),
            kwargs={},
        )
        self.cro_callback = None

        self.first_daq_timestamp = None
        if get_clock_info("time").resolution > 1e-5:
            ts, pc = time_perfcounter_correlation()
            self.timestamp_origin = ts
            self.datetime_origin = datetime.fromtimestamp(ts)
            self.perf_counter_origin = pc
        else:
            self.timestamp_origin = time()
            self.datetime_origin = datetime.fromtimestamp(
                self.timestamp_origin)

            # we will later use this to know if the current platform has a high
            # resolution time.time implementation
            self.perf_counter_origin = -1

        self.pre_send_timestamp = time()
        self.post_send_timestamp = time()
        self.recv_timestamp = time()
コード例 #41
0
    def __init__(self, stdscreen):
        curses.curs_set(0)
        height, width = stdscreen.getmaxyx()
        if height < self.MIN_HEIGHT:
            raise TerminalTooSmallError("The terminal height is too small")
        if width < self.SCREEN_WIDTH + self.INFO_WIDTH:
            raise TerminalTooSmallError("The terminal widht is too small")
        if time.get_clock_info('time').resolution > 1e-03:
            raise Exception('Clock too slow for use')

        self.create_game_board(height, width)
        self.create_game_board(height, width)
        active_h, active_w = self.window.getmaxyx()
        self.active_board = ActiveGameArea(active_h - (self.PADDING * 2),
                                           active_w - (self.PADDING * 2))
        self.rightlimit = active_w - (self.PADDING * 2)
        self.create_info_board()
コード例 #42
0
def analyse_time_graham(size_to_test):
    """This function takes list of array and number of trials as argument.
It prints time taken to perfrom giftwrap algorithm for given lists"""

    if sys.version_info < (3, 3):
        get_time = time.clock
    else:
        get_time = time.perf_counter
        REZ = time.get_clock_info('perf_counter').resolution

    list_to_test = generate_random_array(size_to_test)
    start = get_time()
    sol = grahamscan_e(list_to_test)
    end = get_time()

    time_taken_per_locate = end - start
    return time_taken_per_locate
コード例 #43
0
ファイル: test_time.py プロジェクト: juleskt/ek128_work
    def test_get_clock_info(self):
        clocks = ["clock", "perf_counter", "process_time", "time"]
        if hasattr(time, "monotonic"):
            clocks.append("monotonic")

        for name in clocks:
            info = time.get_clock_info(name)
            # self.assertIsInstance(info, dict)
            self.assertIsInstance(info.implementation, str)
            self.assertNotEqual(info.implementation, "")
            self.assertIsInstance(info.monotonic, bool)
            self.assertIsInstance(info.resolution, float)
            # 0.0 < resolution <= 1.0
            self.assertGreater(info.resolution, 0.0)
            self.assertLessEqual(info.resolution, 1.0)
            self.assertIsInstance(info.adjustable, bool)

        self.assertRaises(ValueError, time.get_clock_info, "xxx")
コード例 #44
0
ファイル: test_time.py プロジェクト: 5outh/Databases-Fall2014
    def test_get_clock_info(self):
        clocks = ['clock', 'perf_counter', 'process_time', 'time']
        if hasattr(time, 'monotonic'):
            clocks.append('monotonic')

        for name in clocks:
            info = time.get_clock_info(name)
            #self.assertIsInstance(info, dict)
            self.assertIsInstance(info.implementation, str)
            self.assertNotEqual(info.implementation, '')
            self.assertIsInstance(info.monotonic, bool)
            self.assertIsInstance(info.resolution, float)
            # 0.0 < resolution <= 1.0
            self.assertGreater(info.resolution, 0.0)
            self.assertLessEqual(info.resolution, 1.0)
            self.assertIsInstance(info.adjustable, bool)

        self.assertRaises(ValueError, time.get_clock_info, 'xxx')
コード例 #45
0
    def __init__(self,
                 data_name="runtime",
                 full_name="Runtime",
                 precision=DEFAULT_PRECISION,
                 **value_input_kwargs):
        runtime_data_type = brokkr.pipeline.datavalue.DataType(
            name=data_name,
            binary_type="d",
            full_name=full_name,
            unit="s",
            uncertainty=max(
                time.get_clock_info("monotonic").resolution,
                1 / (10**precision)))
        super().__init__(data_types=[runtime_data_type],
                         binary_decoder=False,
                         **value_input_kwargs)

        self._precision = precision
コード例 #46
0
ファイル: gpiocounter.py プロジェクト: project-mjolnir/brokkr
    def get_count(self, period_s=None, mean=False):
        if not period_s:
            count = len(self._count_times)
        else:
            # Tabulate the number of counts over a given period
            count = -1
            for count, count_time in enumerate(reversed(self._count_times)):
                if count_time < (time.monotonic() - period_s):
                    break
            else:
                count += 1

        if mean:
            count = count / max([
                min([self.time_elapsed_s, period_s]),
                time.get_clock_info("time").resolution
            ])

        return count
コード例 #47
0
ファイル: test_time.py プロジェクト: FFMG/myoddweb.piger
    def test_thread_time(self):
        if not hasattr(time, 'thread_time'):
            if sys.platform.startswith(('linux', 'win')):
                self.fail("time.thread_time() should be available on %r"
                          % (sys.platform,))
            else:
                self.skipTest("need time.thread_time")

        # thread_time() should not include time spend during a sleep
        start = time.thread_time()
        time.sleep(0.100)
        stop = time.thread_time()
        # use 20 ms because thread_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        info = time.get_clock_info('thread_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #48
0
ファイル: base_events.py プロジェクト: davidsansome/cpython
 def __init__(self):
     self._timer_cancelled_count = 0
     self._closed = False
     self._ready = collections.deque()
     self._scheduled = []
     self._default_executor = None
     self._internal_fds = 0
     # Identifier of the thread running the event loop, or None if the
     # event loop is not running
     self._thread_id = None
     self._clock_resolution = time.get_clock_info("monotonic").resolution
     self._exception_handler = None
     self.set_debug((not sys.flags.ignore_environment and bool(os.environ.get("PYTHONASYNCIODEBUG"))))
     # In debug mode, if the execution of a callback or a step of a task
     # exceed this duration in seconds, the slow callback/task is logged.
     self.slow_callback_duration = 0.1
     self._current_handle = None
     self._task_factory = None
     self._coroutine_wrapper_set = False
コード例 #49
0
    def test_thread_time(self):
        if not hasattr(time, 'thread_time'):
            if sys.platform.startswith(('linux', 'win')):
                self.fail("time.thread_time() should be available on %r" %
                          (sys.platform, ))
            else:
                self.skipTest("need time.thread_time")

        # thread_time() should not include time spend during a sleep
        start = time.thread_time()
        time.sleep(0.100)
        stop = time.thread_time()
        # use 20 ms because thread_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        info = time.get_clock_info('thread_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #50
0
    def test_monotonic(self):
        # monotonic() should not go backward
        times = [time.monotonic() for n in range(100)]
        t1 = times[0]
        for t2 in times[1:]:
            self.assertGreaterEqual(t2, t1, "times=%s" % times)
            t1 = t2

        # monotonic() includes time elapsed during a sleep
        t1 = time.monotonic()
        time.sleep(0.5)
        t2 = time.monotonic()
        dt = t2 - t1
        self.assertGreater(t2, t1)
        self.assertAlmostEqual(dt, 0.5, delta=0.2)

        # monotonic() is a monotonic but non adjustable clock
        info = time.get_clock_info('monotonic')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #51
0
ファイル: test_time.py プロジェクト: Illirgway/cpython
    def test_monotonic(self):
        # monotonic() should not go backward
        times = [time.monotonic() for n in range(100)]
        t1 = times[0]
        for t2 in times[1:]:
            self.assertGreaterEqual(t2, t1, "times=%s" % times)
            t1 = t2

        # monotonic() includes time elapsed during a sleep
        t1 = time.monotonic()
        time.sleep(0.5)
        t2 = time.monotonic()
        dt = t2 - t1
        self.assertGreater(t2, t1)
        self.assertAlmostEqual(dt, 0.5, delta=0.2)

        # monotonic() is a monotonic but non adjustable clock
        info = time.get_clock_info('monotonic')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #52
0
ファイル: test_time.py プロジェクト: 5outh/Databases-Fall2014
    def test_monotonic(self):
        # monotonic() should not go backward
        times = [time.monotonic() for n in range(100)]
        t1 = times[0]
        for t2 in times[1:]:
            self.assertGreaterEqual(t2, t1, "times=%s" % times)
            t1 = t2

        # monotonic() includes time elapsed during a sleep
        t1 = time.monotonic()
        time.sleep(0.5)
        t2 = time.monotonic()
        dt = t2 - t1
        self.assertGreater(t2, t1)
        # Issue #20101: On some Windows machines, dt may be slightly low
        self.assertTrue(0.45 <= dt <= 1.0, dt)

        # monotonic() is a monotonic but non adjustable clock
        info = time.get_clock_info('monotonic')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #53
0
ファイル: metadata.py プロジェクト: hobbestigrou/perf
def _collect_python_metadata(metadata):
    # Implementation
    if hasattr(sys, 'implementation'):
        # PEP 421, Python 3.3
        metadata['python_implementation'] = sys.implementation.name
    else:
        # Convert to lower case to use the same format than Python 3
        _add(metadata, 'python_implementation',
             platform.python_implementation().lower())

    version = platform.python_version()
    bits = platform.architecture()[0]
    if bits:
        version = '%s (%s)' % (version, bits)
    metadata['python_version'] = version
    _add(metadata, 'python_executable', sys.executable)

    # Before PEP 393 (Python 3.3)
    if sys.version_info < (3, 3):
        if sys.maxunicode == 0xffff:
            unicode_impl = 'UTF-16'
        else:
            unicode_impl = 'UCS-4'
        metadata['python_unicode'] = unicode_impl

    # timer
    if (hasattr(time, 'perf_counter')
       and perf.perf_counter == time.perf_counter):

        info = time.get_clock_info('perf_counter')
        metadata['timer'] = ('%s, resolution: %s'
                             % (info.implementation,
                                perf._format_timedelta(info.resolution)))
    elif perf.perf_counter == time.clock:
        metadata['timer'] = 'time.clock()'
    elif perf.perf_counter == time.time:
        metadata['timer'] = 'time.time()'
コード例 #54
0
ファイル: pybench.py プロジェクト: 10sr/cpython
    def main(self):

        rounds = self.values['-n']
        reportfile = self.values['-f']
        show_bench = self.values['-s']
        compare_to = self.values['-c']
        hidenoise = self.values['-d']
        warp = int(self.values['-w'])
        withgc = self.values['--with-gc']
        limitnames = self.values['-t']
        if limitnames:
            if _debug:
                print('* limiting test names to one with substring "%s"' % \
                      limitnames)
            limitnames = re.compile(limitnames, re.I)
        else:
            limitnames = None
        verbose = self.verbose
        withsyscheck = self.values['--with-syscheck']
        calibration_runs = self.values['-C']
        timer = self.values['--timer']

        print('-' * LINE)
        print('PYBENCH %s' % __version__)
        print('-' * LINE)
        print('* using %s %s' % (
            getattr(platform, 'python_implementation', lambda:'Python')(),
            ' '.join(sys.version.split())))

        # Switch off garbage collection
        if not withgc:
            try:
                import gc
            except ImportError:
                print('* Python version doesn\'t support garbage collection')
            else:
                try:
                    gc.disable()
                except NotImplementedError:
                    print('* Python version doesn\'t support gc.disable')
                else:
                    print('* disabled garbage collection')

        # "Disable" sys check interval
        if not withsyscheck:
            # Too bad the check interval uses an int instead of a long...
            value = 2147483647
            try:
                sys.setcheckinterval(value)
            except (AttributeError, NotImplementedError):
                print('* Python version doesn\'t support sys.setcheckinterval')
            else:
                print('* system check interval set to maximum: %s' % value)

        if timer == TIMER_SYSTIMES_PROCESSTIME:
            import systimes
            print('* using timer: systimes.processtime (%s)' % \
                  systimes.SYSTIMES_IMPLEMENTATION)
        else:
            # Check that the clock function does exist
            try:
                get_timer(timer)
            except TypeError:
                print("* Error: Unknown timer: %s" % timer)
                return

            print('* using timer: %s' % timer)
            if hasattr(time, 'get_clock_info'):
                info = time.get_clock_info(timer[5:])
                print('* timer: resolution=%s, implementation=%s'
                      % (info.resolution, info.implementation))

        print()

        if compare_to:
            try:
                f = open(compare_to,'rb')
                bench = pickle.load(f)
                bench.name = compare_to
                f.close()
                compare_to = bench
            except IOError as reason:
                print('* Error opening/reading file %s: %s' % (
                    repr(compare_to),
                    reason))
                compare_to = None

        if show_bench:
            try:
                f = open(show_bench,'rb')
                bench = pickle.load(f)
                bench.name = show_bench
                f.close()
                bench.print_header()
                if compare_to:
                    bench.print_comparison(compare_to,
                                           hidenoise=hidenoise,
                                           limitnames=limitnames)
                else:
                    bench.print_benchmark(hidenoise=hidenoise,
                                          limitnames=limitnames)
            except IOError as reason:
                print('* Error opening/reading file %s: %s' % (
                    repr(show_bench),
                    reason))
                print()
            return

        if reportfile:
            print('Creating benchmark: %s (rounds=%i, warp=%i)' % \
                  (reportfile, rounds, warp))
            print()

        # Create benchmark object
        bench = Benchmark(reportfile,
                          verbose=verbose,
                          timer=timer,
                          warp=warp,
                          calibration_runs=calibration_runs)
        bench.rounds = rounds
        bench.load_tests(Setup, limitnames=limitnames)
        try:
            bench.calibrate()
            bench.run()
        except KeyboardInterrupt:
            print()
            print('*** KeyboardInterrupt -- Aborting')
            print()
            return
        bench.print_header()
        if compare_to:
            bench.print_comparison(compare_to,
                                   hidenoise=hidenoise,
                                   limitnames=limitnames)
        else:
            bench.print_benchmark(hidenoise=hidenoise,
                                  limitnames=limitnames)

        # Ring bell
        sys.stderr.write('\007')

        if reportfile:
            try:
                f = open(reportfile,'wb')
                bench.name = reportfile
                pickle.dump(bench,f)
                f.close()
            except IOError as reason:
                print('* Error opening/writing reportfile %s: %s' % (
                    reportfile,
                    reason))
                print()
コード例 #55
0
from .compatibility import asyncio_ensure_future
from .exceptions import ConnectionClosed, InvalidState
from .framing import *
from .protocol import CLOSED, CONNECTING, WebSocketCommonProtocol


# Unit for timeouts. May be increased on slow machines by setting the
# WEBSOCKETS_TESTS_TIMEOUT_FACTOR environment variable.
MS = 0.001 * int(os.environ.get('WEBSOCKETS_TESTS_TIMEOUT_FACTOR', 1))

# asyncio's debug mode has a 10x performance penalty for this test suite.
if os.environ.get('PYTHONASYNCIODEBUG'):                    # pragma: no cover
    MS *= 10

# Ensure that timeouts are larger than the clock's resolution (for Windows).
MS = max(MS, 2.5 * time.get_clock_info('monotonic').resolution)


class TransportMock(unittest.mock.Mock):
    """
    Transport mock to control the protocol's inputs and outputs in tests.

    It calls the protocol's connection_made and connection_lost methods like
    actual transports.

    To simulate incoming data, tests call the protocol's data_received and
    eof_received methods directly.

    They could also pause_writing and resume_writing to test flow control.

    """
コード例 #56
0
ファイル: test_time.py プロジェクト: juleskt/ek128_work
 def test_time(self):
     time.time()
     info = time.get_clock_info("time")
     self.assertFalse(info.monotonic)
     self.assertTrue(info.adjustable)
コード例 #57
0
ファイル: test_time.py プロジェクト: 5outh/Databases-Fall2014
    def test_clock(self):
        time.clock()

        info = time.get_clock_info('clock')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)
コード例 #58
0
ファイル: test_time.py プロジェクト: Naddiseo/cpython
 def test_time(self):
     time.time()
     info = time.get_clock_info('time')
     self.assertFalse(info.monotonic)
     if sys.platform != 'win32':
         self.assertTrue(info.adjusted)
コード例 #59
0
start_time = my_timer()
#print(start_time)

t.sleep(wait_time)
end_time = my_timer()
#print(end_time)

print(t.localtime(start_time))
print("Started at: " + t.strftime("%X", t.localtime(start_time)))
print(t.localtime(end_time))
print("Finished at: " + t.strftime("%X", t.localtime(end_time)))

print("The interval was {:.4f} seconds".format(end_time - start_time))

from time import perf_counter
from time import monotonic
from time import process_time

print("\nVarious counters:")
print("perf_counter:", perf_counter())
print("monolithic:", monotonic())
print("process_time: (time for CPU perform operations)", process_time())



# built-in function to get info about some of the availbe counters
print('\n', 'clock: ', t.get_clock_info('clock'), sep='', )
print('time:', t.get_clock_info('time'))
print('monotonic:', t.get_clock_info('monotonic'))
print('perf_counter:', t.get_clock_info('perf_counter'))
print('process_time:', t.get_clock_info('process_time'))