本文整理汇总了Python中timeit.clock函数的典型用法代码示例。如果您正苦于以下问题:Python clock函数的具体用法?Python clock怎么用?Python clock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了clock函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: S2
def S2():
var("x y z")
e = (x**sin(x) + y**cos(y) + z**(x + y))**100
t1 = clock()
f = e.expand()
t2 = clock()
return t2 - t1
开发者ID:cbehan,项目名称:symengine,代码行数:7,代码来源:symbench_def.py
示例2: testit
def testit(line):
print line
t1 = clock()
exec line
t2 = clock()
elapsed = t2-t1
print "Time:", elapsed, "for", line, "(OK)"
开发者ID:fperez,项目名称:sympy,代码行数:7,代码来源:torture.py
示例3: S1
def S1():
var('x,y,z')
f = (x+y+z+1)**7
t1 = clock()
g = expand(f*(f+1))
t2 = clock()
return t2 - t1
开发者ID:Upabjojr,项目名称:symengine,代码行数:7,代码来源:symbench_sage.py
示例4: R3
def R3():
var('x,y,z')
f = x+y+z
t1 = clock()
a = [bool(f==f) for _ in range(10)]
t2 = clock()
return t2 - t1
开发者ID:Upabjojr,项目名称:symengine,代码行数:7,代码来源:symbench_sage.py
示例5: doctests
def doctests():
try:
import psyco
psyco.full()
except ImportError:
pass
import sys
from timeit import default_timer as clock
filter = []
for i, arg in enumerate(sys.argv):
if '__init__.py' in arg:
filter = [sn for sn in sys.argv[i+1:] if not sn.startswith("-")]
break
import doctest
globs = globals().copy()
for obj in globs: #sorted(globs.keys()):
if filter:
if not sum([pat in obj for pat in filter]):
continue
sys.stdout.write(str(obj) + " ")
sys.stdout.flush()
t1 = clock()
doctest.run_docstring_examples(globs[obj], {}, verbose=("-v" in sys.argv))
t2 = clock()
print(round(t2-t1, 3))
开发者ID:AALEKH,项目名称:sympy,代码行数:25,代码来源:__init__.py
示例6: perform_search
def perform_search(from_city, to_city, region, metric):
start = clock()
for res, _, progress in nb.best_match(from_city, to_city, region, 900,
progressive=True,
metric=metric):
# print(progress)
try:
distance, r_vids, center, radius = res
except (ValueError, TypeError):
import json
desc = {"type": "Feature", "properties":
{"nb_venues": len(res),
"venues": res,
"origin": from_city},
"geometry": region}
with open('scratch.json', 'a') as out:
out.write(json.dumps(desc, sort_keys=True, indent=2,
separators=(',', ': '))+'\n')
return
if len(center) == 2:
center = c.euclidean_to_geo(to_city, center)
relevant = {'dst': distance, 'radius': radius, 'center': center,
'nb_venues': len(r_vids)}
SEARCH_STATUS.update(dict(seen=False, progress=progress, res=relevant))
print("done search in {:.3f}".format(clock() - start))
SEARCH_STATUS.update(dict(seen=False, progress=1.0, done=True,
res=relevant))
开发者ID:daureg,项目名称:illalla,代码行数:27,代码来源:ServeNN.py
示例7: _compute_rpi
def _compute_rpi(self):
E = self.Etrain
N = self.N
G = {u: set() for u in range(N)}
for v, u in E:
G[u].add(v)
cst = np.log(self.beta/(1-self.beta))
incoming = [[] if len(G[i]) == 0 else sorted(G[i]) for i in range(N)]
wincoming = [np.array([self.lambda_1 * E[(j, i)] for j in ins])
for i, ins in enumerate(incoming)]
pi = self.beta*np.ones(N)
sstart = clock()
nb_iter, eps = 0, 1
while eps > self.tol and nb_iter < self.n_iters:
next_pi = np.zeros_like(pi)
for i in range(N):
if not incoming[i]:
continue
pij = pi[incoming[i]]
ratio = pij/(1 + np.exp(-cst - wincoming[i]))
opp_prod = np.exp(np.log(1-pij).sum())
next_pi[i] = (ratio.sum() + self.beta*opp_prod)/(pij.sum() + opp_prod)
eps = (np.abs(next_pi - pi)/pi).mean()
pi = next_pi.copy()
nb_iter += 1
self.time_taken += clock() - sstart
self.rpi = pi
开发者ID:daureg,项目名称:magnet,代码行数:27,代码来源:rank_nodes.py
示例8: higher_request
def higher_request(start_time, bbox, db, level=0):
""" Try to insert all photos in this region into db by potentially making
recursing call, eventually to lower_request when the region accounts for
less than 4000 photos. """
if level > 20:
logging.warn("Going too deep with {}.".format(bbox))
return 0
_, total = make_request(start_time, bbox, 1, need_answer=True,
max_tries=10)
if level == 0:
logging.info('Aiming for {} photos'.format(total))
if total > 4000:
photos = 0
start = clock()
quads = split_bbox(bbox)
for q in quads:
photos += higher_request(start_time, q, db, level+1)
logging.info('Finish {}: {} photos in {}s'.format(bbox, photos,
clock()-start))
return photos
if total > 5:
return lower_request(start_time, bbox, db, total/PER_PAGE + 1)
logging.warn('Cannot get any photos in {}.'.format(bbox))
return 0
开发者ID:daureg,项目名称:illalla,代码行数:25,代码来源:grab_photos.py
示例9: pairs
def pairs(name, data, labels=None):
""" Generate something similar to R `pairs` """
nvariables = data.shape[1]
mpl.rcParams["figure.figsize"] = 3.5 * nvariables, 3.5 * nvariables
if labels is None:
labels = ["var {}".format(i) for i in range(nvariables)]
fig = plt.figure()
s = clock()
for i in range(nvariables):
for j in range(i, nvariables):
nsub = i * nvariables + j + 1
ax = fig.add_subplot(nvariables, nvariables, nsub)
ax.tick_params(left="off", bottom="off", right="off", top="off", labelbottom="off", labelleft="off")
ax.spines["top"].set_visible(False)
ax.spines["left"].set_linewidth(0.5)
ax.spines["bottom"].set_linewidth(0.5)
ax.spines["right"].set_visible(False)
if i == j:
ppl.hist(ax, data[:, i], grid="y")
ax.set_title(labels[i], fontsize=10)
else:
ax.set_xlim([data[:, i].min(), data[:, i].max()])
ax.set_ylim([data[:, j].min(), data[:, j].max()])
ax.scatter(data[:, i], data[:, j], marker=".", color="k", s=4)
ax.tick_params(labelbottom="off", labelleft="off")
print(clock() - s)
s = clock()
plt.savefig(name + "_corr.png", dpi=96, transparent=False, frameon=False, bbox_inches="tight", pad_inches=0.1)
print(clock() - s)
开发者ID:morgz,项目名称:illalla,代码行数:29,代码来源:plot_corr.py
示例10: timing
def timing(f, *args, **kwargs):
"""
Returns time elapsed for evaluating ``f()``. Optionally arguments
may be passed to time the execution of ``f(*args, **kwargs)``.
If the first call is very quick, ``f`` is called
repeatedly and the best time is returned.
"""
once = kwargs.get('once')
if 'once' in kwargs:
del kwargs['once']
if args or kwargs:
if len(args) == 1 and not kwargs:
arg = args[0]
g = lambda: f(arg)
else:
g = lambda: f(*args, **kwargs)
else:
g = f
from timeit import default_timer as clock
t1=clock(); v=g(); t2=clock(); t=t2-t1
if t > 0.05 or once:
return t
for i in range(3):
t1=clock();
# Evaluate multiple times because the timer function
# has a significant overhead
g();g();g();g();g();g();g();g();g();g()
t2=clock()
t=min(t,(t2-t1)/10)
return t
开发者ID:KevinGoodsell,项目名称:sympy,代码行数:31,代码来源:usertools.py
示例11: CreateGraph
def CreateGraph(textFile, nLetters):
pickleFileName = 'wordList'+str(nLetters)+'.pkl'
try:
wordList = pickle.load(open(pickleFileName,'r'))
return wordList
except:
start = clock()
inFile = open(textFile, 'r')
wordList = {}
for word in inFile:
word = word.rstrip().lower()
if len(word) == nLetters:
wordList[word] = [] #good, ignores duplicates
maimed = {}
for word in wordList:
for altWord in GetMaimedWords(word):
if altWord not in maimed:
maimed[altWord] = []
maimed[altWord].append(word)
print 'Time taken = %.5f' %(clock()-start)
for word in wordList:
for maimWord in GetMaimedWords(word):
for altWord in maimed[maimWord]:
if altWord not in wordList[word] and altWord != word:
wordList[word].append(altWord)
print 'Created pre-processed graph in %.5f seconds' % (clock()-start)
pickle.dump(wordList, open(pickleFileName, 'w'))
return wordList
开发者ID:robj137,项目名称:Fun,代码行数:28,代码来源:HeadTail.py
示例12: R7
def R7():
var('x')
f = x**24+34*x**12+45*x**3+9*x**18 +34*x**10+ 32*x**21
t1 = clock()
a = [f.subs({x: random()}) for _ in xrange(10^4)]
t2 = clock()
return t2 - t1
开发者ID:rohanaru53,项目名称:symengine,代码行数:7,代码来源:symbench_sage.py
示例13: S3a
def S3a():
var('x,y,z')
f = expand((x**y + y**z + z**x)**500)
t1 = clock()
g = f.diff(x)
t2 = clock()
return t2 - t1
开发者ID:Upabjojr,项目名称:symengine,代码行数:7,代码来源:symbench_sage.py
示例14: S1
def S1():
var("x y z")
e = (x+y+z+1)**7
f = e*(e+1)
t1 = clock()
f = f.expand()
t2 = clock()
return t2 - t1
开发者ID:cbehan,项目名称:symengine,代码行数:8,代码来源:symbench_def.py
示例15: run_benchmark
def run_benchmark(n):
x, y = symbols("x y")
e = (1 + sqrt(3) * x + sqrt(5) * y) ** n
f = e * (e + sqrt(7))
t1 = clock()
f = expand(f)
t2 = clock()
print("%s ms" % (1000 * (t2 - t1)))
开发者ID:parsoyaarihant,项目名称:symengine.py,代码行数:8,代码来源:expand7.py
示例16: testit
def testit(line):
if filt in line:
print(line)
t1 = clock()
exec_(line, globals(), locals())
t2 = clock()
elapsed = t2-t1
print("Time:", elapsed, "for", line, "(OK)")
开发者ID:AdrianPotter,项目名称:sympy,代码行数:8,代码来源:torture.py
示例17: S3a
def S3a():
var("x y z")
e = (x**y + y**z + z**x)**500
e = e.expand()
t1 = clock()
f = e.diff(x)
t2 = clock()
return t2 - t1
开发者ID:cbehan,项目名称:symengine,代码行数:8,代码来源:symbench_def.py
示例18: run_benchmark
def run_benchmark(n):
var("x y z w")
e = (x + y + z + w)**n
f = e * (e + w)
t1 = clock()
g = f.expand()
t2 = clock()
print("%s ms" % (1000 * (t2 - t1)))
开发者ID:parsoyaarihant,项目名称:symengine.py,代码行数:8,代码来源:expand2.py
示例19: R2
def R2():
def hermite(n,y):
if n == 1: return 2*y
if n == 0: return 1
return expand(2*y*hermite(n-1,y) - 2*(n-1)*hermite(n-2,y))
t1 = clock()
hermite(15,var('y'))
t2 = clock()
return t2 - t1
开发者ID:Upabjojr,项目名称:symengine,代码行数:9,代码来源:symbench_sage.py
示例20: inputhook_wx3
def inputhook_wx3():
"""Run the wx event loop by processing pending events only.
This is like inputhook_wx1, but it keeps processing pending events
until stdin is ready. After processing all pending events, a call to
time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
This sleep time should be tuned though for best performance.
"""
# We need to protect against a user pressing Control-C when IPython is
# idle and this is running. We trap KeyboardInterrupt and pass.
try:
app = wx.GetApp()
if app is not None:
assert wx.Thread_IsMain()
# The import of wx on Linux sets the handler for signal.SIGINT
# to 0. This is a bug in wx or gtk. We fix by just setting it
# back to the Python default.
if not callable(signal.getsignal(signal.SIGINT)):
signal.signal(signal.SIGINT, signal.default_int_handler)
evtloop = wx.EventLoop()
ea = wx.EventLoopActivator(evtloop)
t = clock()
while not stdin_ready():
while evtloop.Pending():
t = clock()
evtloop.Dispatch()
app.ProcessIdle()
# We need to sleep at this point to keep the idle CPU load
# low. However, if sleep to long, GUI response is poor. As
# a compromise, we watch how often GUI events are being processed
# and switch between a short and long sleep time. Here are some
# stats useful in helping to tune this.
# time CPU load
# 0.001 13%
# 0.005 3%
# 0.01 1.5%
# 0.05 0.5%
used_time = clock() - t
if used_time > 5*60.0:
# print 'Sleep for 5 s' # dbg
time.sleep(5.0)
elif used_time > 10.0:
# print 'Sleep for 1 s' # dbg
time.sleep(1.0)
elif used_time > 0.1:
# Few GUI events coming in, so we can sleep longer
# print 'Sleep for 0.05 s' # dbg
time.sleep(0.05)
else:
# Many GUI events coming in, so sleep only very little
time.sleep(0.001)
del ea
except KeyboardInterrupt:
pass
return 0
开发者ID:cournape,项目名称:ipython,代码行数:57,代码来源:inputhookwx.py
注:本文中的timeit.clock函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论