本文整理汇总了Python中timeit.clock函数的典型用法代码示例。如果您正苦于以下问题:Python clock函数的具体用法?Python clock怎么用?Python clock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了clock函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例2: testit
def testit(line):
print line
t1 = clock()
exec line
t2 = clock()
elapsed = t2-t1
print "Time:", elapsed, "for", line, "(OK)"
示例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
示例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
示例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))
示例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))
示例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
示例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
示例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)
示例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
示例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
示例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
示例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
示例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
示例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)))