• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python time.now函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中time.now函数的典型用法代码示例。如果您正苦于以下问题:Python now函数的具体用法?Python now怎么用?Python now使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了now函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: writeSynFile

	def writeSynFile(self, altIndexList):
		"""
		Build .syn file
		"""
		if not altIndexList:
			return

		log.info("Sorting %s synonyms..." % len(altIndexList))
		t0 = now()

		altIndexList.sort(
			key=lambda x: sortKeyBytes(x[0])
		)
		# 28 seconds with old sort key (converted from custom cmp)
		# 0.63 seconds with my new sort key
		# 0.20 seconds without key function (default sort)

		log.info("Sorting %s synonyms took %.2f seconds" % (
			len(altIndexList),
			now() - t0,
		))
		log.info("Writing %s synonyms..." % len(altIndexList))
		t0 = now()
		with open(self._filename+".syn", "wb") as synFile:
			synFile.write(b"".join([
				b_alt + b"\x00" + intToBinStr(wordIndex, 4)
				for b_alt, wordIndex in altIndexList
			]))
		log.info("Writing %s synonyms took %.2f seconds" % (
			len(altIndexList),
			now() - t0,
		))
开发者ID:ilius,项目名称:pyglossary,代码行数:32,代码来源:stardict.py


示例2: find_best_lin

def find_best_lin(train,test):
	best_r=0
	T=[]
	for pen in [0.1,0.5,1,10,50]:
		start=now()
		clf=svm.LinearSVC(C=pen,class_weight="auto")
		clf.fit(train[:,2:18],train[:,1])
		finish=now()
		T.append(finish-start)
		scores=clf.predict(test[:,2:18])
		print pen
		scaled_score=scores
		# for i in range(len(scores)):
		# 	scaled_score[i]=(scores[i]-min(scores))/(max(scores)-min(scores))

		fpr, tpr, thresholds = roc_curve(test[:,1], scaled_score)
		roc_auc = auc(fpr, tpr)
		print roc_auc
		r_score=clf.score(test[:,2:18],test[:,1])
		if best_r<roc_auc:
			best_clf=clf
			best_r=roc_auc
			best_pen=pen
			best_scores=scaled_score
	return best_pen,best_r,best_clf,best_scores,T
开发者ID:zhangpu0703,项目名称:DataMining_CreditScoring,代码行数:25,代码来源:test.py


示例3: wrapped

 def wrapped(*args, **kwargs):
     start = now()
     result = func(*args, **kwargs)
     end = now()
     ms_delta = (end - start) * 1000
     print "Execution time: {0}ms".format(ms_delta)
     return result
开发者ID:chr1sbest,项目名称:blog.chrisbest,代码行数:7,代码来源:decorators4.py


示例4: make_the_timeseries

def make_the_timeseries():
    print('Read and filter data')
    # Load data from the star
    time, flux = kic.getdata(ID, kernelsize, quarter, sigma, noisecut)
    #time = time[:((len(time)+1)//2)]
    #flux = flux[:((len(flux)+1)//2)]
    assert len(time) == len(flux)

    # Calculate and print Nyquist-frequency
    dt = np.diff(time)
    nyquist = 1 / (2 * np.median(dt))
    print('Nyquist frequency: %s µHz' % str(nyquist))

    # Plot the time series
    """
    plt.figure()
    plt.plot(time, flux, 'k.')
    plt.xlabel(r'Relative time [Ms]')
    plt.ylabel(r'Photometry')
    plt.xlim([np.amin(time), np.amax(time)])
    plt.savefig('%s_time.pdf' % (starname), bbox_inches='tight')
    """

    # Save data in textfile
    print('Write %d entries to %s' % (len(time), ts))
    timerStart = now()

    savenpz(ts, np.transpose([time, flux]))

    elapsedTime = now() - timerStart
    print('Took %.2f s' % elapsedTime)
开发者ID:amaliestokholm,项目名称:asteroseismology,代码行数:31,代码来源:asteroseismic_analysis_stokholm.py


示例5: _wait_until_ready

    def _wait_until_ready(self, timeout=5, raise_if_not_ready=True):
        # we're only ready when it's possible to connect to the CrossBar
        # over TCP - so let's just try it.
        end = now() + timeout
        ready = False

        while not ready:
            timeout = end - now()
            if timeout < 0:
                if raise_if_not_ready:
                    raise ConnectionError(
                        'Failed to connect to CrossBar over {}: {}:{}'.format(
                            self.ipv, self.host, self.port)
                    )
                else:
                    return ready

            try:
                self.try_connection()
            except ConnectionError:
                pass
            else:
                ready = True

        return ready
开发者ID:noisyboiler,项目名称:wampy,代码行数:25,代码来源:routers.py


示例6: main

def main():
    path = u'D:\\test2'
    all_md5 = {}
    all_size = {}
    total_file = 0
    total_delete = 0
    start = now()
    print("start")
    for file in os.listdir(path):
        total_file += 1
        real_path = os.path.join(path, file)
        if os.path.isfile(real_path):
            size = os.stat(real_path).st_size
            name_and_md5 = [real_path, '']
            if size in all_size.keys():
                print('finded')
                new_md5 = getmd5(real_path)
                if all_size[size][1] == '':
                    all_size[size][1] = getmd5(all_size[size][0])
                if new_md5 in all_size[size]:
                    print("DELETE:" + file)
                    os.remove(path+'\\'+file)
                    total_delete += 1
                else:
                    all_size[size].append(new_md5)
            else:
                all_size[size] = name_and_md5
    end = now()
    time_last = end - start
    print('TOTAL NUMBER:', total_file)
    print('DELETED NUMBER:', total_delete)
    print('TIME COST:', time_last, 'SEC')
开发者ID:alleninshell,项目名称:delete_same_files,代码行数:32,代码来源:quchong.py


示例7: main

def main():
    path = raw_input("Path: ")
    all_size = {}
    total_file = 0
    total_delete = 0
    start = now()

    for file in os.listdir(path):
        total_file += 1;
        real_path = os.path.join(path, file)
        if os.path.isfile(real_path) == True:
            filesize = os.stat(real_path).st_size
            name_md5 = [real_path, '']
            if filesize in all_size.keys():
                new_md5 = getmd5(real_path)
                if all_size[filesize][1] == '':
                    all_size[filesize][1] = getmd5(all_size[filesize][0])
                if new_md5 in all_size[filesize]:
                    total_delete += 1
                    os.remove(real_path)
                    print 'Delete ', file
                else:
                    all_size[filesize].append(new_md5)
            else:
                all_size[filesize] = name_md5
    end = now()
    time_last = end - start

    print 'File total: ', total_file
    print 'Del  total: ', total_delete
    print 'Time consuming: ', time_last, 's'
开发者ID:nearilezz,项目名称:Scripts,代码行数:31,代码来源:DelRepeat.py


示例8: count_or_show_by_generator

def count_or_show_by_generator(gen, count_enable, row_count, col_count):
    """
    gen: a generator returned by find_solutions_*
    count_enable: bool, only count solutions/configurations, don't show them
    """
    if count_enable:
        print('Calculating, please wait... (Control+C to cancel)')
        tm0 = now()
        try:
            solution_count = sum(1 for _ in gen)
        except KeyboardInterrupt:
            print('\nGoodbye')
            return
        delta = now() - tm0
        print('Number of Unique Configurations: %s' % solution_count)
        print('Running Time: %.4f seconds' % delta)
    else:
        print('Found Configurations:\n')
        for board in gen:
            print(format_board(board, row_count, col_count))
            try:
                input('Press Enter to see the next, Control+C to exit')
            except KeyboardInterrupt:
                print('\nGoodbye')
                break
开发者ID:ilius,项目名称:chess-challenge,代码行数:25,代码来源:main.py


示例9: main

def main():
    path = input("path:")
    all_size = {}  
    total_file = 0 
    total_delete = 0 
    start = now()  
    for file in os.listdir(path):  
        total_file += 1  
        real_path = os.path.join(path, file)  
        if os.path.isfile(real_path) == True:  
            size = os.stat(real_path).st_size  
            name_and_md5 = [real_path, '']  
            if size in all_size.keys():  
                new_md5 = getmd5(real_path)  
                if all_size[size][1] == '':  
                    all_size[size][1] = getmd5(all_size[size][0])  
                if new_md5 in all_size[size]:  
                    print ('删除'), file  
                    total_delete += 1  
                else:  
                    all_size[size].append(new_md5)  
            else:  
                all_size[size] = name_and_md5  
    end = now()  
    time_last = end - start  
    print ('文件总数:'), total_file  
    print ('删除个数:'), total_delete  
    print ('耗时:'), time_last, '秒'  
开发者ID:linkenpeng,项目名称:python,代码行数:28,代码来源:删除一个文件夹下面的重复文件.py


示例10: __init__

	def __init__(sz, start_position, r_winch, c, looptime, armflag):
			
		#Lengths set the initial configuration of the system.
        	# Lengths: array 1x4 [L0, L1, L2, L3]
        	#create spiral zipper object
        	#physical notes
        	#sz ckbot direction: CCW subtracts tether and CW adds/releases tether.
		sz.startposition = start_position
		sz.start_detected = False
		sz.entered = False
		sz.tether_subtract_CCW = True
		sz.looptime = looptime  #control speed to be enforced
		sz.timeold = 0
		sz.timeold2 = 0

		sz.goal_prev = start_position
		sz.goal_start = now()
		sz.goal_stop =now()
		sz.target_achieved = [0, 0]
		sz.target_reached = False
		sz.P = 10*np.eye(2) #System covariance. Trust in initial Process Model Conditions
		sz.Q = 0.01*np.eye(2) #System noise Covariance. What we think the initial process noise is
		sz.R = 1*np.eye(2) #Sensor Noise Covariance. What we think of the sensor noise is. 

		got_port = [1, 1, 1]

		ser = [0, 0, 0]

		try:
			ser[0] = serial.Serial('/dev/ttyACM0', 57600)
		except Exception, e:
			print "No Arduino on ACM0"
			print str(e)
			got_port[0] = 0
开发者ID:siddarthbs,项目名称:APC-control,代码行数:34,代码来源:spiral_zipper_auto.py


示例11: compare_find_solutions_time

def compare_find_solutions_time():
    """
    run and compare the running time of 3 implementations of find_solutions
    """

    row_count, col_count, count_by_symbol = input_problem()

    time_list = []

    func_list = (
        find_solutions_s,
        find_solutions_r,
        find_solutions_q,
        find_solutions_s,
        find_solutions_r,
        find_solutions_q,
    )

    for func in func_list:  # pylint!
        tm0 = now()
        for _ in func(row_count, col_count, count_by_symbol):
            pass
        delta = now() - tm0
        time_list.append(delta)
        print('%.4f seconds   (%s)' % (delta, func))
开发者ID:ilius,项目名称:chess-challenge,代码行数:25,代码来源:main.py


示例12: pb47

def pb47():
    n = 0
    n1 = []
    n2 = []
    n3 = []
    print(now())
    primes = simpleseive(200000)
    print(now())
    while n < 200000:
        m = n
        n4 = []
        for p in primes:
            #print(m,p)
            if p > m:
                break
            if m % p == 0:
                while m % p == 0:
                    m = m / p
                    #print(m,p)
                n4.append(p)
                if len(n4) == 5:
                    break
        if len(n4) == len(n3) == len(n2) == len(n1)== 4:
            print(n-3,n-2,n-1,n,n*(n-1)*(n-2)*(n-3))
            return
        #print(n1,n2,n3,n4)
        n1,n2,n3 = n2 + [],n3 + [],n4 + []
        n += 1
    print(now())
开发者ID:mikegw,项目名称:project_euler,代码行数:29,代码来源:47.py


示例13: wait_net_service

def wait_net_service(host, port, timeout=None):
    import socket
    from time import sleep, time as now
    log('Waiting for web server: ' + host + ':' + str(port))

    s = socket.socket()
    if timeout:
        end = now() + timeout

    while True:
        try:
            if timeout:
                if now() > end:
                    log('ERROR! Network sockets connect waiting timeout!')
                    return False

            s.connect((host, port))

        except socket.timeout:
            sleep(0.1)
            pass
        except socket.error:
            sleep(0.1)
            pass

        else:
            s.close()
            return True
开发者ID:kolomenkin,项目名称:limbo,代码行数:28,代码来源:test_server.py


示例14: change_status

def change_status(target, status):
    target_name = target.getName()
    old_status = None
    if target_name in busy_players:
        value = busy_players[target_name]
        time_left = value[1] - now()
        if time_left > 0:
            msg(target, "&cYou must wait %.2fs untill you can change your status" % time_left)
            return
        old_status = value[0]

    if old_status is status:
        if status is True:
            msg(target, "&cYou are already SUPER busy")
        elif status is False:
            msg(target, "&cYou are already busy")
        else:
            msg(target, "&cYou weren't busy yet")
        return

    busy_players[target_name] = (status, now() + busy_status_change_timeout)
    if status is True:
        broadcast(None, target.getDisplayName() + " &7is now SUPER busy")
    elif status is False:
        broadcast(None, target.getDisplayName() + " &7is now busy")
    else:
        broadcast(None, target.getDisplayName() + " &7is not busy anymore")
开发者ID:RedstonerServer,项目名称:redstoner-utils,代码行数:27,代码来源:imbusy.py


示例15: wait_net_service

def wait_net_service(server, port, timeout=None):
    """ Wait for network service to appear
        @param timeout: in seconds, if None or 0 wait forever
        @return: True of False, if timeout is None may return only True or
                 throw unhandled network exception
    """

    s = socket.socket()
    if timeout:
        from time import time as now
        # time module is needed to calc timeout shared between two exceptions
        end = now() + timeout

    while True:
        try:
            if timeout:
                next_timeout = end - now()
                if next_timeout < 0:
                    return False
                else:
                    s.settimeout(next_timeout)

            s.connect((server, port))

        except socket.timeout, err:
            # this exception occurs only if timeout is set
            if timeout:
                return False

        except socket.error, err:
            # catch timeout exception from underlying network library
            # this one is different from socket.timeout
            pass
开发者ID:telefonicaid,项目名称:fiware-testbed-deploy,代码行数:33,代码来源:change_idm_password.py


示例16: _wait_net_service

def _wait_net_service(server, port, timeout=None):
    """ Wait for network service to appear
        @param timeout: in seconds, if None or 0 wait forever
        @return: True of False, if timeout is None may return only True or
                 throw unhandled network exception
    """
    s = socket.socket()
    if timeout:
        end = now() + timeout

    while True:
        try:
            if timeout:
                next_timeout = end - now()
                if next_timeout < 0:
                    return False
                else:
                    s.settimeout(next_timeout)

            s.connect((server, port))

        except socket.timeout:
            # this exception occurs only if timeout is set
            if timeout:
                return False

        except socket.error:
            pass
        else:
            s.close()
            return True
开发者ID:adefelicibus,项目名称:planemo,代码行数:31,代码来源:shed_app_test_utils.py


示例17: __init__

    def __init__(self, test_data_fn):
        start = now()
        if os.path.isfile(test_data_fn):
            print("Reading test data...")
            self.prepop_rows, self.idens, self.props, self.rows = \
                pickle.load(open(test_data_fn, 'rb'))
        else:
            print("Generating test data...")
            random.seed(4)  # 4 chosen by fair dice roll.  Guaranteed to be random
            forms = [gen_random_form() for x in range(NUM_FORMS)]
            # FIXME:  don't use random.choice!!! Super duper slow
            self.prepop_rows = flatten(_rows_from_tufo(gen_random_tufo(random.choice(forms)))
                                       for x in range(NUM_PREEXISTING_TUFOS))
            tufos = [gen_random_tufo(random.choice(forms)) for x in range(NUM_TUFOS)]
            self.idens = [t[0] for t in tufos]
            self.props = [get_random_keyval(t[1]) for t in tufos]
            random.shuffle(self.idens)
            random.shuffle(self.props)

            self.rows = flatten(_rows_from_tufo(x) for x in tufos)
            pickle.dump((self.prepop_rows, self.idens, self.props, self.rows),
                        open(test_data_fn, 'wb'))

        print("Test data generation took: %.2f" % (now() - start))
        print('addRows: # Tufos:%8d, # Rows: %8d' % (NUM_TUFOS, len(self.rows)))
        print('len count: small:%d, medium:%d, large:%d, huge:%d' %
              (small_count, medium_count, large_count, huge_count))
开发者ID:vivisect,项目名称:synapse,代码行数:27,代码来源:benchmark_cortex.py


示例18: deep_search

def deep_search(task, timeout=10*60):
    state = State.from_task(task)
    solution = Solution(task)
    solution.metrics = state.estimator.metrics
    deadline = now() + timeout

    # Python has no tail-recursion optimization.
    # Even more, python has a limit on recursion depth
    # So, we need to write big loops iteratively

    while state:  # when we try to .negate() init state we will obtain None and will exit from the loop
        solution.steps += 1
        if not state.is_feasible:
            state = state.parent
            continue

        if state.is_all_covered():
            solution.store_result(state)
            state = state.negate()  # try to deselect the current set or rollback to the parent state
            continue

        if state.get_optimistic_cost() >= solution.best_cost:
            if now() > deadline:  # we get to this place often enough to stop in time,
                                  # and we get to it not on the each iteration, so we will not check the time too frequently
                return solution
            state = state.negate()  # try to deselect the current set or rollback to the parent state
            continue

        state = state.next_child()

    solution.proven_as_optimal = True  # we have not terminated on timeout, so we have explored all the tree
    return solution
开发者ID:discreteoptimization,项目名称:setcover,代码行数:32,代码来源:cp_solver.py


示例19: any_unknown

 def any_unknown(self, message, *args, **kwargs):
     found = False
     key = (message, repr(args), repr(kwargs))
     try:
         value = self._cache.peek(key)
     except KeyError:
         pass
     else:
         found = True
         if not self._cache.hasExpired(key):
             raise StopIteration(value)
     if self._backoffStarted:
         if self._backoffStarted + self._backoffTimeout < now():
             self._backoffStarted = None
         elif found:
             raise StopIteration(value)
         else:
             raise BackoffException()
     try:
         value = yield self.any.unknown(message, *args, **kwargs)
         self._cache[key] = value
     except (SystemExit, KeyboardInterrupt, AssertionError):
         raise
     except Exception, e:
         if self._backoffTimeout and isinstance(e, TimeoutException):
             self._backoffStarted = now()
             if not (self._returnCachedValueInCaseOfException and found):
                 raise BackoffException()
         if not (self._returnCachedValueInCaseOfException and found):
             raise
开发者ID:seecr,项目名称:meresco-components,代码行数:30,代码来源:timedmessagecache.py


示例20: write_func

 def write_func(ident):
     with lock.write_lock():
         enter_time = now()
         time.sleep(WORK_TIMES[ident % len(WORK_TIMES)])
         exit_time = now()
         start_stops.append((lock.WRITER, enter_time, exit_time))
         time.sleep(NAPPY_TIME)
开发者ID:javierpena,项目名称:fasteners,代码行数:7,代码来源:test_lock.py



注:本文中的time.now函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python time.perf_counter函数代码示例发布时间:2022-05-27
下一篇:
Python time.monotonic函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap