本文整理汇总了Python中timeit.default_timer方法的典型用法代码示例。如果您正苦于以下问题:Python timeit.default_timer方法的具体用法?Python timeit.default_timer怎么用?Python timeit.default_timer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类timeit
的用法示例。
在下文中一共展示了timeit.default_timer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def main():
t1 = timeit.default_timer()
with ProcessPoolExecutor(max_workers=4) as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
print("{} Seconds Needed for ProcessPoolExecutor".format(timeit.default_timer() - t1))
t2 = timeit.default_timer()
with ThreadPoolExecutor(max_workers=4) as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
print("{} Seconds Needed for ThreadPoolExecutor".format(timeit.default_timer() - t2))
t3 = timeit.default_timer()
for number in PRIMES:
isPrime = is_prime(number)
print("{} is prime: {}".format(number, isPrime))
print("{} Seconds needed for single threaded execution".format(timeit.default_timer()-t3))
示例2: run
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def run(self):
request = self.request
try:
if ((timeit.default_timer() - self.starttime) <= self.timeout and
not SHUTDOWN_EVENT.isSet()):
try:
f = urlopen(request)
except TypeError:
# PY24 expects a string or buffer
# This also causes issues with Ctrl-C, but we will concede
# for the moment that Ctrl-C on PY24 isn't immediate
request = build_request(self.request.get_full_url(),
data=request.data.read(self.size))
f = urlopen(request)
f.read(11)
f.close()
self.result = sum(self.request.data.total)
else:
self.result = 0
except (IOError, SpeedtestUploadTimeout):
self.result = sum(self.request.data.total)
示例3: interp_rcut
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def interp_rcut(self, ff, rr, rcut=None):
""" Interpolation of vector data ff[...,:] and vector arguments rr[:] """
assert ff.shape[-1]==self.nr
ffa = ff.reshape(ff.size//self.nr, self.nr)
if rcut is None: rcut = self.gg[-1]
rra = rr.reshape(-1) if type(rr)==np.ndarray else np.array([rr])
#t0 = timer()
r2l,r2k,ir2cc = self.coeffs_rcut(rra, rcut)
#t1 = timer()
fr2v = np.zeros(ffa.shape[0:-1]+rra.shape[:])
#print(__name__, fr2v.shape, fr2v[:,r2l[0]].shape, r2l[0].shape)
#print(__name__, 'ff ', type(ff))
for j in range(6): fr2v[:,r2l[0]]+= ffa[:,r2k+j]*ir2cc[j]
#t2 = timer()
#print(__name__, 'times: ', t1-t0, t2-t1)
return fr2v.reshape((ff.shape[0:-1]+rr.shape[:]))
示例4: init_prod_basis_pp
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def init_prod_basis_pp(self, sv, **kvargs):
""" Talman's procedure should be working well with Pseudo-Potential starting point."""
from pyscf.nao.m_prod_biloc import prod_biloc_c
#t1 = timer()
self.init_inp_param_prod_log_dp(sv, **kvargs)
data = self.chain_data()
libnao.init_vrtx_cc_apair(data.ctypes.data_as(POINTER(c_double)), c_int64(len(data)))
self.sv_pbloc_data = True
#t2 = timer(); print(t2-t1); t1=timer();
self.bp2info = [] # going to be some information including indices of atoms, list of contributing centres, conversion coefficients
for ia1 in range(sv.natoms):
rc1 = sv.ao_log.sp2rcut[sv.atom2sp[ia1]]
for ia2 in range(ia1+1,sv.natoms):
rc2,dist = sv.ao_log.sp2rcut[sv.atom2sp[ia2]], sqrt(((sv.atom2coord[ia1]-sv.atom2coord[ia2])**2).sum())
if dist>rc1+rc2 : continue
pbiloc = self.comp_apair_pp_libint(ia1,ia2)
if pbiloc is not None : self.bp2info.append(pbiloc)
self.dpc2s,self.dpc2t,self.dpc2sp = self.init_c2s_domiprod() # dominant product's counting
self.npdp = self.dpc2s[-1]
self.norbs = self.sv.norbs
return self
示例5: rf0_cmplx_ref
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def rf0_cmplx_ref(self, ww):
""" Full matrix response in the basis of atom-centered product functions """
rf0 = np.zeros((len(ww), self.nprod, self.nprod), dtype=self.dtypeComplex)
v = self.pb.get_ac_vertex_array()
t1 = timer()
if self.verbosity>1: print(__name__, 'self.ksn2e', self.ksn2e, len(ww))
zvxx_a = zeros((len(ww), self.nprod), dtype=self.dtypeComplex)
for s in range(self.nspin):
n2e = self.ksn2e[0,s,:]
n2f = self.ksn2f[0,s,:]
n2x = self.x[s,:,:]
for en,fn,xn in zip(n2e,n2f,n2x):
vx = dot(v, xn)
for em,fm,xm in zip(n2e,n2f,n2x):
vxx_a = dot(vx, xm.T)
for iw,comega in enumerate(ww):
zvxx_a[iw,:] = vxx_a * (fn - fm)/ (comega - (em - en))
rf0 += einsum('wa,b->wab', zvxx_a, vxx_a)
t2 = timer()
if self.verbosity>0: print(__name__, 'rf0_ref_loop', t2-t1)
return rf0
示例6: get_k
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def get_k(self, dm=None, **kw):
'''Compute K matrix for the given density matrix.'''
from pyscf.nao.m_kmat_den import kmat_den
if dm is None: dm = self.make_rdm1()
if False:
print(__name__, ' get_k: self.kmat_algo ', self.kmat_algo, dm.shape)
if len(dm.shape)==5:
print(__name__, 'nelec dm', (dm[0,:,:,:,0]*self.overlap_lil().toarray()).sum())
elif len(dm.shape)==2 or len(dm.shape)==3:
print(__name__, 'nelec dm', (dm*self.overlap_lil().toarray()).sum())
else:
print(__name__, dm.shape)
kmat_algo = kw['kmat_algo'] if 'kmat_algo' in kw else self.kmat_algo
#if self.verbosity>1: print(__name__, "\t\t====> Matrix elements of Fock exchange operator will be calculated by using '{}' algorithm.\f".format(kmat_algo))
return kmat_den(self, dm=dm, algo=kmat_algo, **kw)
if self.kmat_timing is not None: t1 = timer()
kmat = kmat_den(self, dm=dm, algo=kmat_algo, **kw)
if self.kmat_timing is not None: self.kmat_timing += timer()-t1
return kmat
示例7: test_log_interp_vv_speed
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def test_log_interp_vv_speed(self):
""" Test the interpolation facility for an array arguments from the class log_interp_c """
rr,pp = funct_log_mesh(1024, 0.01, 200.0)
lgi = log_interp_c(rr)
gcs = np.array([1.2030, 3.2030, 0.7, 10.0, 5.3])
ff = np.array([[np.exp(-gc*r**2) for r in rr] for gc in gcs])
rr = np.linspace(0.05, 250.0, 2000000)
t1 = timer()
fr2yy = lgi.interp_rcut(ff, rr, rcut=16.0)
t2 = timer()
#print(__name__, 't2-t1: ', t2-t1)
yyref = np.exp(-(gcs.reshape(gcs.size,1)) * (rr.reshape(1,rr.size)**2))
self.assertTrue(np.allclose(fr2yy, yyref) )
示例8: test_rsh_vec
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def test_rsh_vec(self):
""" Compute real spherical harmonics via a vectorized algorithm """
from pyscf.nao.m_rsphar_libnao import rsphar_exp_vec as rsphar_exp_vec_libnao
from pyscf.nao.m_rsphar_vec import rsphar_vec as rsphar_vec_python
from timeit import default_timer as timer
ll = [0,1,2,3,4]
crds = np.random.rand(20000, 3)
for lmax in ll:
t1 = timer()
rsh1 = rsphar_exp_vec_libnao(crds.T, lmax)
t2 = timer(); tpython = (t2-t1); t1 = timer()
rsh2 = rsphar_vec_libnao(crds, lmax)
t2 = timer(); tlibnao = (t2-t1); t1 = timer()
#print( abs(rsh1.T-rsh2).sum(), tpython, tlibnao)
# print( rsh1[1,:])
# print( rsh2[1,:])
示例9: test_log_interp_vv_speed_and_space
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def test_log_interp_vv_speed_and_space(self):
""" Test the interpolation facility for an array arguments from the class log_interp_c """
rr,pp = funct_log_mesh(1024, 0.01, 200.0)
lgi = log_interp_c(rr)
gcs = np.array([1.2030, 3.2030, 0.7, 10.0, 5.3])
ff = np.array([[np.exp(-gc*r**2) for r in rr] for gc in gcs])
rrs = np.linspace(0.05, 250.0, 2000000)
t1 = timer()
fr2yy1 = lgi.interp_csr(ff, rrs, rcut=16.0)
t2 = timer()
#print(__name__, 't1: ', t2-t1)
#print(fr2yy1.shape, fr2yy1.size)
yyref = np.exp(-(gcs.reshape(gcs.size,1)) * (rrs.reshape(1,rrs.size)**2))
self.assertTrue(np.allclose(fr2yy1.toarray(), yyref) )
示例10: test_matelem_speed
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def test_matelem_speed(self):
""" Test the computation of atomic orbitals in coordinate space """
dname = os.path.dirname(os.path.abspath(__file__))
mf = mf_c(verbosity=0, label='water', cd=dname, gen_pb=False, force_gamma=True, Ecut=50)
g = mf.mesh3d.get_3dgrid()
t0 = timer()
vna = mf.vna(g.coords)
t1 = timer()
ab2v1 = mf.matelem_int3d_coo(g, vna)
t2 = timer()
ab2v2 = mf.matelem_int3d_coo_ref(g, vna)
t3 = timer()
#print(__name__, 't1 t2: ', t1-t0, t2-t1, t3-t2)
#print(abs(ab2v1.toarray()-ab2v2.toarray()).sum()/ab2v2.size, (abs(ab2v1.toarray()-ab2v2.toarray()).max()))
self.assertTrue(np.allclose(ab2v1.toarray(), ab2v2.toarray()))
示例11: test_ao_eval_speed
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def test_ao_eval_speed(self):
""" Test the computation of atomic orbitals in coordinate space """
dname = os.path.dirname(os.path.abspath(__file__))
mf = mf_c(verbosity=0, label='water', cd=dname, gen_pb=False, force_gamma=True, Ecut=20)
g = mf.mesh3d.get_3dgrid()
t0 = timer()
oc2v1 = mf.comp_aos_den(g.coords)
t1 = timer()
oc2v2 = mf.comp_aos_py(g.coords)
t2 = timer()
print(__name__, 't1 t2: ', t1-t0, t2-t1)
print(abs(oc2v1-oc2v2).sum()/oc2v2.size, (abs(oc2v1-oc2v2).max()))
self.assertTrue(np.allclose(oc2v1, oc2v2, atol=3.5e-5))
示例12: test_0078_vhartree_pbc_water
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def test_0078_vhartree_pbc_water(self):
""" Test Hartree potential on equidistant grid with Periodic Boundary Conditions """
import os
dname = os.path.dirname(os.path.abspath(__file__))
mf = mf_c(label='water', cd=dname, gen_pb=False, Ecut=100.0)
d = abs(np.dot(mf.ucell_mom(), mf.ucell)-(2*np.pi)*np.eye(3)).sum()
self.assertTrue(d<1e-15)
g = mf.mesh3d.get_3dgrid()
dens = mf.dens_elec(g.coords, mf.make_rdm1()).reshape(mf.mesh3d.shape)
ts = timer()
vh = mf.vhartree_pbc(dens)
tf = timer()
#print(__name__, tf-ts)
E_Hartree = 0.5*(vh*dens*g.weights).sum()*HARTREE2EV
self.assertAlmostEqual(E_Hartree, 382.8718239023864)
# siesta: Hartree = 382.890331
示例13: test_update
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def test_update():
# lower case, tokenized.
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
trade_tracker = TRADETracker()
trade_tracker.init_session()
trade_tracker.state['history'] = [
['null', 'i am trying to find an restaurant in the center'],
['the cambridge chop is an good restaurant']
]
from timeit import default_timer as timer
start = timer()
pprint(trade_tracker.update('what is the area ?'))
end = timer()
print(end - start)
start = timer()
pprint(trade_tracker.update('what is the area '))
end = timer()
print(end - start)
示例14: _timed_block_factory
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def _timed_block_factory(opening_text):
from timeit import default_timer as timer
from traceback import format_exception
from sys import exc_info
def _timed_block_decorator(s, before=None, after=None):
display(opening_text, s)
def wrapper(func):
if callable(before):
before()
time = timer()
try:
func()
except AssertionError as e:
display('FAILED', str(e))
except Exception:
fail('Unexpected exception raised')
tb_str = ''.join(format_exception(*exc_info()))
display('ERROR', tb_str)
display('COMPLETEDIN', '{:.2f}'.format((timer() - time) * 1000))
if callable(after):
after()
return wrapper
return _timed_block_decorator
示例15: log_duration
# 需要导入模块: import timeit [as 别名]
# 或者: from timeit import default_timer [as 别名]
def log_duration(fn: Callable):
functools.wraps(fn)
def timed_function(*args, **kwargs):
start_time = timeit.default_timer()
try:
result = fn(*args, **kwargs)
finally:
elapsed = timeit.default_timer() - start_time
elapsed_str = human_readable(elapsed)
message_detail = get_detail(fn.__name__)
logger.info(f"Completed {message_detail}validation in {elapsed_str}.\n")
return result
return timed_function