def wolframalpha(inp, bot=None):
"""wa <query> -- Computes <query> using Wolfram Alpha."""
server = 'http://api.wolframalpha.com/v2/query.jsp'
api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
if not api_key:
return formatting.output('WolframAlpha', ['error: missing api key'])
import time
start = time.clock()
scantimeout = '3.0'
podtimeout = '4.0'
formattimeout = '8.0'
async = 'True'
waeo = WolframAlphaEngine(api_key, server)
waeo.ScanTimeout = scantimeout
waeo.PodTimeout = podtimeout
waeo.FormatTimeout = formattimeout
waeo.Async = async
python类clock()的实例源码
def greenlet_profiler(event, args):
if event in ('switch', 'throw'): # both events are in the target context
now = clock()
try:
# we need to account the time for the user function
frame = sys._getframe(1)
except ValueError:
# the first greenlet.switch() and when the greenlet is being
# destroied there is nothing more in the stack, so this function is
# the first function called
frame = sys._getframe(0)
origin, target = args
origin_state = _state[origin]
target_state = ensure_thread_state(target, frame)
origin_state.switch_enter(now) # origin is entering the "sleep" state
target_state.switch_exit(now) # target might be leaving the "sleep"
def write_file_update_progress(self, cmd: str, callback: Callable, filesize: int=0, blocksize: int=8192, rest: bool=None) -> str:
self.ftps.voidcmd('TYPE I') # type: ignore
with self.ftps.transfercmd(cmd, rest) as conn: # type: ignore
self.current_download['filesize'] = filesize
self.current_download['downloaded'] = 0
self.current_download['filename'] = cmd.replace('RETR ', '')
start = time.clock()
while 1:
data = conn.recv(blocksize)
if not data:
break
downloaded = len(data)
self.current_download['downloaded'] += downloaded
current = time.clock()
if current > start:
self.current_download['speed'] = self.current_download['downloaded'] / ((current - start) * 1024)
callback(data)
self.current_download['filename'] = ''
self.current_download['speed'] = 0
self.current_download['filesize'] = 0
# shutdown ssl layer
if _SSLSocket is not None and isinstance(conn, _SSLSocket):
conn.unwrap()
return self.ftps.voidresp() # type: ignore
def _add_timeout(self, fd):
if fd._timeout:
self._lock.acquire()
fd._timeout_id = _time() + fd._timeout + 0.0001
i = bisect_left(self._timeouts, (fd._timeout_id, fd))
self._timeouts.insert(i, (fd._timeout_id, fd))
if self._polling:
self.interrupt()
self._lock.release()
else:
fd._timeout_id = None
def _add_timeout(self, fd):
if fd._timeout:
fd._timeout_id = _time() + fd._timeout + 0.0001
i = bisect_left(self._timeouts, (fd._timeout_id, fd))
self._timeouts.insert(i, (fd._timeout_id, fd))
else:
fd._timeout_id = None
def wait(self, timeout=None):
"""Must be used with 'yield' as 'yield cv.wait()'.
"""
task = Pycos.cur_task(self._scheduler)
if self._owner != task:
raise RuntimeError('"%s"/%s: invalid lock release - owned by "%s"/%s' %
(task._name, task._id, self._owner._name, self._owner._id))
assert self._depth > 0
depth = self._depth
self._depth = 0
self._owner = None
if self._waitlist:
wake = self._waitlist.pop(0)
wake._proceed_(True)
self._notifylist.append(task)
start = _time()
if (yield task._await_(timeout)) is None:
try:
self._notifylist.remove(task)
except ValueError:
pass
raise StopIteration(False)
while self._owner is not None:
self._waitlist.insert(0, task)
if timeout is not None:
timeout -= (_time() - start)
if timeout <= 0:
raise StopIteration(False)
start = _time()
if (yield task._await_(timeout)) is None:
try:
self._waitlist.remove(task)
except ValueError:
pass
raise StopIteration(False)
assert self._depth == 0
self._owner = task
self._depth = depth
raise StopIteration(True)
def _suspend(self, task, timeout, alarm_value, state):
"""Internal use only. See sleep/suspend in Task.
"""
self._lock.acquire()
if self.__cur_task != task:
self._lock.release()
logger.warning('invalid "suspend" - "%s" != "%s"', task, self.__cur_task)
return -1
tid = task._id
if state == Pycos._AwaitMsg_ and task._msgs:
s, update = task._msgs[0]
if s == state:
task._msgs.popleft()
self._lock.release()
return update
if timeout is None:
task._timeout = None
else:
if not isinstance(timeout, (float, int)):
logger.warning('invalid timeout %s', timeout)
self._lock.release()
return -1
if timeout <= 0:
self._lock.release()
return alarm_value
else:
task._timeout = _time() + timeout + 0.0001
heappush(self._timeouts, (task._timeout, tid, alarm_value))
self._scheduled.discard(tid)
self._suspended.add(tid)
task._state = state
self._lock.release()
return 0
def _add_timeout(self, fd):
if fd._timeout:
self._lock.acquire()
fd._timeout_id = _time() + fd._timeout + 0.0001
i = bisect_left(self._timeouts, (fd._timeout_id, fd))
self._timeouts.insert(i, (fd._timeout_id, fd))
if self._polling:
self.interrupt()
self._lock.release()
else:
fd._timeout_id = None
def acquire(self, blocking=True, timeout=-1):
"""Must be used with 'yield' as 'yield rlock.acquire()'.
"""
if not self._scheduler:
self._scheduler = Pycos.scheduler()
task = Pycos.cur_task(self._scheduler)
if self._owner == task:
assert self._depth > 0
self._depth += 1
raise StopIteration(True)
if not blocking and self._owner is not None:
raise StopIteration(False)
if timeout < 0:
timeout = None
while self._owner is not None:
if timeout is not None:
if timeout <= 0:
raise StopIteration(False)
start = _time()
self._waitlist.append(task)
if (yield task._await_(timeout)) is None:
try:
self._waitlist.remove(task)
except ValueError:
pass
if timeout is not None:
timeout -= (_time() - start)
assert self._depth == 0
self._owner = task
self._depth = 1
raise StopIteration(True)
def acquire(self, blocking=True, timeout=-1):
"""Must be used with 'yield' as 'yield cv.acquire()'.
"""
if not self._scheduler:
self._scheduler = Pycos.scheduler()
task = Pycos.cur_task(self._scheduler)
if self._owner == task:
self._depth += 1
raise StopIteration(True)
if not blocking and self._owner is not None:
raise StopIteration(False)
if timeout < 0:
timeout = None
while self._owner is not None:
if timeout is not None:
if timeout <= 0:
raise StopIteration(False)
start = _time()
self._waitlist.append(task)
if (yield task._await_(timeout)) is None:
try:
self._waitlist.remove(task)
except ValueError:
pass
if timeout is not None:
timeout -= (_time() - start)
assert self._depth == 0
self._owner = task
self._depth = 1
raise StopIteration(True)
def wait(self, timeout=None):
"""Must be used with 'yield' as 'yield cv.wait()'.
"""
task = Pycos.cur_task(self._scheduler)
if self._owner != task:
raise RuntimeError('"%s"/%s: invalid lock release - owned by "%s"/%s' %
(task._name, task._id, self._owner._name, self._owner._id))
assert self._depth > 0
depth = self._depth
self._depth = 0
self._owner = None
if self._waitlist:
wake = self._waitlist.pop(0)
wake._proceed_(True)
self._notifylist.append(task)
start = _time()
if (yield task._await_(timeout)) is None:
try:
self._notifylist.remove(task)
except ValueError:
pass
raise StopIteration(False)
while self._owner is not None:
self._waitlist.insert(0, task)
if timeout is not None:
timeout -= (_time() - start)
if timeout <= 0:
raise StopIteration(False)
start = _time()
if (yield task._await_(timeout)) is None:
try:
self._waitlist.remove(task)
except ValueError:
pass
raise StopIteration(False)
assert self._depth == 0
self._owner = task
self._depth = depth
raise StopIteration(True)
def receive(self, category=None, timeout=None, alarm_value=None):
"""Similar to 'receive' of Task, except it retrieves (waiting, if
necessary) messages in given 'category'.
"""
# assert Pycos.cur_task() == self._task
c = self._categories.get(category, None)
if c:
msg = c.popleft()
raise StopIteration(msg)
if timeout:
start = _time()
while 1:
msg = yield self._task.receive(timeout=timeout, alarm_value=alarm_value)
if msg == alarm_value:
raise StopIteration(msg)
for categorize in self._categorize:
c = categorize(msg)
if c == category:
raise StopIteration(msg)
if c is not None:
bucket = self._categories.get(c, None)
if not bucket:
bucket = self._categories[c] = collections.deque()
bucket.append(msg)
break
else:
self._categories[None].append(msg)
if timeout:
now = _time()
timeout -= now - start
start = now
def __init__(self, direction, latency, kbps):
self.direction = direction
self.latency = latency
self.kbps = kbps
self.queue = Queue.Queue()
self.last_tick = time.clock()
self.next_message = None
self.available_bytes = .0
self.peer = 'server'
if self.direction == self.PIPE_IN:
self.peer = 'client'
def tick(self):
global connections
global flush_pipes
processed_messages = False
now = time.clock()
try:
if self.next_message is None:
self.next_message = self.queue.get_nowait()
# Accumulate bandwidth if an available packet/message was waiting since our last tick
if self.next_message is not None and self.kbps > .0 and self.next_message['time'] <= now:
elapsed = now - self.last_tick
accumulated_bytes = elapsed * self.kbps * 1000.0 / 8.0
self.available_bytes += accumulated_bytes
# process messages as long as the next message is sendable (latency or available bytes)
while (self.next_message is not None) and\
(flush_pipes or ((self.next_message['time'] <= now) and
(self.kbps <= .0 or self.next_message['size'] <= self.available_bytes))):
self.queue.task_done()
processed_messages = True
if self.kbps > .0:
self.available_bytes -= self.next_message['size']
self.SendPeerMessage(self.next_message)
self.next_message = None
self.next_message = self.queue.get_nowait()
except:
pass
# Only accumulate bytes while we have messages that are ready to send
if self.next_message is None or self.next_message['time'] > now:
self.available_bytes = .0
self.last_tick = now
return processed_messages
########################################################################################################################
# Threaded DNS resolver
########################################################################################################################
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
self.start_time = time.time()
def test_module(module,url,times):
timelist = []
for index in range(times):
try :
start = time.clock()
obj = module.urlopen(url)
timelist.append((time.clock()-start))
except:
continue
#if isinstance(obj,httpx.ResponseHandler):
# print(obj.http_header('statuscode'))
return timelist
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
self.start_time = time.time()
def _get_time_times(timer=os.times):
t = timer()
return t[0] + t[1]
# Using getrusage(3) is better than clock(3) if available:
# on some systems (e.g. FreeBSD), getrusage has a higher resolution
# Furthermore, on a POSIX system, returns microseconds, which
# wrap around after 36min.
def process_sample(self, signal_frame):
if self.profile:
start = time.clock()
if signal_frame:
stack = self.recover_stack(signal_frame)
if stack:
self.update_profile(self.profile, stack)
stack = None
self.profile._overhead += (time.clock() - start)
def process_queue(self, ticks_per_sec):
"""Process the entire queue while taking periodic breaks. This allows
the game loop to run smoothly. The queue contains calls to
_show_block() and _hide_block() so this method should be called if
add_block() or remove_block() was called with immediate=False
"""
start = time.clock()
while self.show_hide_queue and time.clock() - start < 1.0 / ticks_per_sec:
self._dequeue()