當前位置: 首頁>>代碼示例>>Python>>正文


Python timeit.default_timer方法代碼示例

本文整理匯總了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)) 
開發者ID:PacktPublishing,項目名稱:Learning-Concurrency-in-Python,代碼行數:22,代碼來源:poolImprovement.py

示例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) 
開發者ID:NatanaelAntonioli,項目名稱:L.E.S.M.A,代碼行數:23,代碼來源:L.E.S.M.A. - Fabrica de Noobs Speedtest.py

示例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[:])) 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:19,代碼來源:m_log_interp.py

示例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 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:26,代碼來源:m_prod_basis_obsolete.py

示例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 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:26,代碼來源:m_rf0_den.py

示例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 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:25,代碼來源:scf.py

示例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) ) 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:18,代碼來源:test_0202_log_interp_vv.py

示例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,:]) 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:21,代碼來源:test_0031_rsh_vec.py

示例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) ) 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:20,代碼來源:test_0203_log_interp_speed_ram.py

示例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())) 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:19,代碼來源:test_0205_matelem_ram.py

示例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)) 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:19,代碼來源:test_0204_ao_eval_speed.py

示例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 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:18,代碼來源:test_0078_vhartree_pbc_water.py

示例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) 
開發者ID:ConvLab,項目名稱:ConvLab,代碼行數:21,代碼來源:trade.py

示例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 
開發者ID:codewars,項目名稱:python-test-framework,代碼行數:27,代碼來源:test_framework.py

示例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 
開發者ID:spectacles-ci,項目名稱:spectacles,代碼行數:18,代碼來源:utils.py


注:本文中的timeit.default_timer方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。