当前位置: 首页>>代码示例>>Python>>正文


Python time.monotonic方法代码示例

本文整理汇总了Python中time.monotonic方法的典型用法代码示例。如果您正苦于以下问题:Python time.monotonic方法的具体用法?Python time.monotonic怎么用?Python time.monotonic使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在time的用法示例。


在下文中一共展示了time.monotonic方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __call__

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def __call__(self, *args: typing.Any, **kwargs: typing.Any) -> typing.Any:
        cur_time_ms = int(time.monotonic() * 1000)
        if self._pending_call is None:
            if (self._last_call_ms is None or
                    cur_time_ms - self._last_call_ms > self._delay_ms):
                # Call right now
                self._last_call_ms = cur_time_ms
                self._func(*args, **kwargs)
                return

            self._timer.setInterval(self._delay_ms -
                                    (cur_time_ms - self._last_call_ms))
            # Disconnect any existing calls, continue if no connections.
            try:
                self._timer.timeout.disconnect()
            except TypeError:
                pass
            self._timer.timeout.connect(self._call_pending)
            self._timer.start()

        # Update arguments for an existing pending call
        self._pending_call = _CallArgs(args=args, kwargs=kwargs) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:24,代码来源:throttle.py

示例2: __init__

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def __init__(
        self,
        log_func: Callable[..., None] = None,
        json_indent: int = 4,
        time_func: Callable[[], float] = None,
    ):
        """
        Initialize a new instance of the dialog test logger.

        :param log_func: A callable method or object that can log a message,
        default to `logging.getLogger(__name__).info`.
        :type log_func: Callable[..., None]
        :param json_indent: An indent for json output, default indent is 4.
        :type json_indent: int
        :param time_func: A time function to record time spans, default to `time.monotonic`.
        :type time_func: Callable[[], float]
        """
        self._log = logging.getLogger(__name__).info if log_func is None else log_func
        self._stopwatch_state_key = f"stopwatch.{uuid.uuid4()}"
        self._json_indent = json_indent
        self._time_func = time.monotonic if time_func is None else time_func 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:23,代码来源:dialog_test_logger.py

示例3: wait_for

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def wait_for(self, predicate, timeout=None):
        """Wait until a condition evaluates to True.

        predicate should be a callable which result will be interpreted as a
        boolean value.  A timeout may be provided giving the maximum time to
        wait.

        """
        endtime = None
        waittime = timeout
        result = predicate()
        while not result:
            if waittime is not None:
                if endtime is None:
                    endtime = _time() + waittime
                else:
                    waittime = endtime - _time()
                    if waittime <= 0:
                        break
            self.wait(waittime)
            result = predicate()
        return result 
开发者ID:war-and-code,项目名称:jawfish,代码行数:24,代码来源:threading.py

示例4: _retry_on_intr

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def _retry_on_intr(fn, timeout):
        if timeout is None:
            deadline = float("inf")
        else:
            deadline = monotonic() + timeout

        while True:
            try:
                return fn(timeout)
            # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7
            except (OSError, select.error) as e:
                # 'e.args[0]' incantation works for both OSError and select.error
                if e.args[0] != errno.EINTR:
                    raise
                else:
                    timeout = deadline - monotonic()
                    if timeout < 0:
                        timeout = 0
                    if timeout == float("inf"):
                        timeout = None
                    continue 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:23,代码来源:wait.py

示例5: acquire

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def acquire(self, blocking=True, timeout=None):
        if not blocking and timeout is not None:
            raise ValueError("can't specify timeout for non-blocking acquire")
        rc = False
        endtime = None
        self._cond.acquire()
        while self._value == 0:
            if not blocking:
                break
            if timeout is not None:
                if endtime is None:
                    endtime = _time() + timeout
                else:
                    timeout = endtime - _time()
                    if timeout <= 0:
                        break
            self._cond.wait(timeout)
        else:
            self._value = self._value - 1
            rc = True
        self._cond.release()
        return rc 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:24,代码来源:thread_util.py

示例6: execute

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def execute(self) -> Generator[events.ExecutionEvent, None, None]:
        """Common logic for all runners."""
        results = TestResultSet()

        initialized = events.Initialized.from_schema(schema=self.schema)
        yield initialized

        for event in self._execute(results):
            if (
                self.exit_first
                and isinstance(event, events.AfterExecution)
                and event.status in (Status.error, Status.failure)
            ):
                break
            yield event

        yield events.Finished.from_results(results=results, running_time=time.monotonic() - initialized.start_time) 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:19,代码来源:core.py

示例7: _wsgi_test

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def _wsgi_test(
    case: Case,
    checks: Iterable[CheckFunction],
    targets: Iterable[Target],
    result: TestResult,
    headers: Dict[str, Any],
    store_interactions: bool,
    feedback: Feedback,
) -> WSGIResponse:
    # pylint: disable=too-many-arguments
    with catching_logs(LogCaptureHandler(), level=logging.DEBUG) as recorded:
        start = time.monotonic()
        response = case.call_wsgi(headers=headers)
        elapsed = time.monotonic() - start
    run_targets(targets, elapsed)
    if store_interactions:
        result.store_wsgi_response(case, response, headers, elapsed)
    result.logs.extend(recorded.records)
    run_checks(case, checks, result, response)
    feedback.add_test_case(case, response)
    return response 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:23,代码来源:core.py

示例8: delay

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def delay(self):
        """Compute the next delay

        Returns the next delay to wait according to the exponential
        backoff algorithm.  This is a value between 0 and base * 2^exp
        where exponent starts off at 1 and is incremented at every
        invocation of this method up to a maximum of 10.

        If a period of more than base * 2^11 has passed since the last
        retry, the exponent is reset to 1.
        """
        invocation = time.monotonic()
        interval = invocation - self._last_invocation
        self._last_invocation = invocation

        if interval > self._reset_time:
            self._exp = 0

        self._exp = min(self._exp + 1, self._max)
        return self._randfunc(0, self._base * 2 ** self._exp) 
开发者ID:Rapptz,项目名称:discord.py,代码行数:22,代码来源:backoff.py

示例9: add

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def add(self, node: Node) -> Node:
        """Try to add the given node to this bucket.

        If the node is already present, it is moved to the tail of the list, and we return None.

        If the node is not already present and the bucket has fewer than k entries, it is inserted
        at the tail of the list, and we return None.

        If the bucket is full, we add the node to the bucket's replacement cache and return the
        node at the head of the list (i.e. the least recently seen), which should be evicted if it
        fails to respond to a ping.
        """
        self.last_updated = time.monotonic()
        if node in self.nodes:
            self.nodes.remove(node)
            self.nodes.append(node)
        elif len(self) < self.k:
            self.nodes.append(node)
        else:
            self.replacement_cache.append(node)
            return self.head
        return None 
开发者ID:QuarkChain,项目名称:pyquarkchain,代码行数:24,代码来源:kademlia.py

示例10: _task_function

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def _task_function(self) -> None:
        next_heartbeat_at = time.monotonic()
        while self._maybe_task:
            try:
                self._call_pre_heartbeat_handlers()
                if self._presentation.transport.local_node_id is not None:
                    if not await self._publisher.publish(self.make_message()):
                        _logger.warning('%s heartbeat send timed out', self)

                next_heartbeat_at += self._publisher.send_timeout
                await asyncio.sleep(next_heartbeat_at - time.monotonic())
            except asyncio.CancelledError:
                _logger.debug('%s publisher task cancelled', self)
                break
            except pyuavcan.transport.ResourceClosedError as ex:
                _logger.debug('%s transport closed, publisher task will exit: %s', self, ex)
                break
            except Exception as ex:
                _logger.exception('%s publisher task exception: %s', self, ex)
        try:
            self._publisher.close()
        except pyuavcan.transport.TransportError:
            pass 
开发者ID:UAVCAN,项目名称:pyuavcan,代码行数:25,代码来源:heartbeat_publisher.py

示例11: __call__

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def __call__(self, cb_args, force_call=False):
        now = time_monotonic()
        prev_call_time = self._prev_call_time
        # _debug(f'CancelCallback: force_call={force_call}, prev_call_time={prev_call_time}, '
        #        f'now={now}, self._interval={self._interval}: {cb_args[1:]}')
        if (force_call or                             # Special case (e.g. exception in Torrent.verify())
            prev_call_time is None or                 # This is the first call
            now - prev_call_time >= self._interval):  # Previous call was at least `interval` seconds ago
            self._prev_call_time = now
            try:
                _debug(f'CancelCallback: Calling callback with {cb_args[1:]}')
                return_value = self._callback(*cb_args)
                if return_value is not None:
                    _debug(f'CancelCallback: Callback cancelled: {return_value!r}')
                    self._cancelled()
                    return True
                return False
            except BaseException as e:
                _debug(f'CancelCallback: Caught exception: {e!r}')
                self._cancelled()
                raise 
开发者ID:rndusr,项目名称:torf,代码行数:23,代码来源:_generate.py

示例12: test_worker_init

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def test_worker_init(self):
        """
        Tests if workers initialize without problems for the pong config.
        """
        agent_config = config_from_path("configs/ray_apex_for_pong.json")

        # Long initialization times can lead to Ray crashes.
        start = time.monotonic()
        executor = ApexExecutor(
            environment_spec=self.env_spec,
            agent_config=agent_config,
        )
        end = time.monotonic() - start
        print("Initialized {} workers in {} s.".format(
            executor.num_sample_workers, end
        ))
        executor.test_worker_init() 
开发者ID:rlgraph,项目名称:rlgraph,代码行数:19,代码来源:test_apex_agent_long_task_learning.py

示例13: profile_time

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def profile_time(trace_name,
                     name,
                     enabled=True,
                     stream=None,
                     end_stream=None):
        """Print time spent by CPU and GPU.

        Useful as a temporary context manager to find sweet spots of code
        suitable for async implementation.
        """
        if (not enabled) or not torch.cuda.is_available():
            yield
            return
        stream = stream if stream else torch.cuda.current_stream()
        end_stream = end_stream if end_stream else stream
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        stream.record_event(start)
        try:
            cpu_start = time.monotonic()
            yield
        finally:
            cpu_end = time.monotonic()
            end_stream.record_event(end)
            end.synchronize()
            cpu_time = (cpu_end - cpu_start) * 1000
            gpu_time = start.elapsed_time(end)
            msg = f'{trace_name} {name} cpu_time {cpu_time:.2f} ms '
            msg += f'gpu_time {gpu_time:.2f} ms stream {stream}'
            print(msg, end_stream) 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:32,代码来源:profiling.py

示例14: _remaining_time

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def _remaining_time(self, endtime):
        """Convenience for _communicate when computing timeouts."""
        if endtime is None:
            return None
        else:
            return endtime - _time() 
开发者ID:war-and-code,项目名称:jawfish,代码行数:8,代码来源:subprocess.py

示例15: _check_timeout

# 需要导入模块: import time [as 别名]
# 或者: from time import monotonic [as 别名]
def _check_timeout(self, endtime, orig_timeout):
        """Convenience for checking if a timeout has expired."""
        if endtime is None:
            return
        if _time() > endtime:
            raise TimeoutExpired(self.args, orig_timeout) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:8,代码来源:subprocess.py


注:本文中的time.monotonic方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。