当前位置: 首页>>代码示例>>Python>>正文


Python time.clock函数代码示例

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


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

示例1: RunTest

def RunTest(testNum, p0, p1, p2, hasAnswer, p3):
    obj = JanuszInTheCasino()
    startTime = time.clock()
    answer = obj.findProbability(p0, p1, p2)
    endTime = time.clock()
    testTime.append(endTime - startTime)
    res = True
    if hasAnswer:
        res = answer == p3
    if res:
        print(str("Test #") + str(testNum) + ": Passed")
        return res
    print(str("Test #") + str(testNum) + str(":"))
    print(("[") + str(p0) + str(",") + str(p1) + str(",") + str(p2) + str("]"))
    if (hasAnswer):
        print(str("Expected:"))
        print(str(p3))

    print(str("Received:"))
    print(str(answer))
    print(str("Verdict:"))
    if (not res):
        print(("Wrong answer!!"))
    elif ((endTime - startTime) >= 20):
        print(str("FAIL the timeout"))
        res = False
    elif (hasAnswer):
        print(str("OK!!"))
    else:
        print(str("OK, but is it right?"))
    print("Time: %.11f seconds" % (endTime - startTime))
    print(str("-----------------------------------------------------------"))
    return res
开发者ID:trunghieu11,项目名称:PythonAlgorithm,代码行数:33,代码来源:JanuszInTheCasino.py

示例2: kontrola

    def kontrola(self, datadir=None):
        """
        Jednoduché vyhodnocení výsledků
        """

        obrazky, reseni = self.readImageDir(datadir)

        vysledky = []

        for i in range(0, len(obrazky)):
            cas1 = time.clock()
            im = skimage.io.imread(obrazky[i])
            result = self.rozpoznejZnacku(im)

            cas2 = time.clock()

            if((cas2 - cas1) >= 1.0):
                print "cas vyprsel"
                result = 0

            vysledky.append(result)

        hodnoceni = np.array(reseni) == np.array(vysledky)
        skore = np.sum(hodnoceni.astype(np.int)) / np.float(len(reseni))

        print skore
开发者ID:mjirik,项目名称:ZDO2014sample_solution,代码行数:26,代码来源:ZDO2014sample_solution.py

示例3: __init__

 def __init__(self, fndark, nblocksize):
     if (os.path.isfile(fndark+'-dark.npz')):
         npzfile=np.load(fndark+'-dark.npz');
         self.dmean=npzfile['dmean'];
         self.dstd=npzfile['dstd'];
         self.dbpm=npzfile['dbpm'];
     else:
         dark=Binary(fndark);
         nframes=dark.nframes; my=dark.my; mx=dark.mx;
         nblocks=nframes//nblocksize;
         
         bmed=np.zeros((nblocks,my,mx));
         bstd=np.zeros((nblocks,my,mx));
         for iblock in range(nblocks):
             t0=time.clock();
             a=dark.data[iblock*nblocksize:(iblock+1)*nblocksize];
             a,idx=dropbadframes(a);
             print '- read block, dropped bad, subtracted dark in '+str(time.clock()-t0)+'s';
             nfb=a.shape[0];                
             bmed[iblock,:,:]=np.median(a,axis=0);
             bstd[iblock,:,:]=np.std(a,axis=0);
         self.dmean=np.mean(bmed,axis=0);
         self.dstd=np.sqrt(np.sum((bstd)**2,axis=0));
         self.dbpm=self.dstd<(np.median(self.dstd)+5*np.std(self.dstd));
         self.dbpm=self.dstd<(np.median(self.dstd*self.dbpm)+5*np.std(self.dstd*self.dbpm));
         
         np.savez(fndark+'-dark',dmean=self.dmean,dstd=self.dstd,dbpm=self.dbpm);
         del dark;
开发者ID:perhansson,项目名称:daq,代码行数:28,代码来源:epix.py

示例4: draw

	def draw(self):
		self.screen.clear_pixel()
		
		start = time.clock() * 2.77 + math.sin(time.clock())
		end = time.clock() * 7.35 + 0.5 * math.pi
		distance = end - start
		start = start % (2 * math.pi)
		end = end % (2 * math.pi)

		invert = distance % (4 * math.pi) > 2 * math.pi
		if invert:
			buf = end
			end = start
			start = buf

		hue = (time.clock() * 0.01) % 1
		color = hsv_to_color(hue, 1, 1)

		for x in range(16):
			for y in range(16):
				r = ((x - 8)**2 + (y - 8)**2)**0.5
				if r == 0:
					r = 0.001
				angle = math.acos((x - 8) / r)
				if y - 8 < 0:
					angle = 2 * math.pi - angle
				if (angle > start and angle < end) or (end < start and (angle > start or angle < end)):
					self.screen.pixel[x][y] = color

		self.screen.update()
开发者ID:Jokelo,项目名称:pixelpi,代码行数:30,代码来源:pie.py

示例5: timing

 def timing(self):
     t0 = time.clock()
     try:
         yield
     finally:
         te = time.clock()
         self.laps.append(te - t0)
开发者ID:douban,项目名称:libmc,代码行数:7,代码来源:runbench.py

示例6: req

def req():
    # Get URLs from a text file, remove white space.
    db = MySQLDatabase(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME)
    db_worker_view = db.get_work_view()
    articles = db_worker_view.retrieve_all_articles()
    #articles = db_worker_view.retrieve_all_articles_questionmark()
    # measure time
    start = time.clock()
    start_time_iteration = start
    iteration_number = 483
    for i, article in enumerate(articles):
        # print some progress
        if i % 10000 == 0:
            #print time for the iteration
            seconds = time.clock() - start_time_iteration
            m, s = divmod(seconds, 60)
            h, m = divmod(m, 60)
            print "Number of crawled articles: %d. Total time for last iteration of 10000 articles: %d:%02d:%02d" % (i, h, m, s)
            start_time_iteration = time.clock()
            iteration_number += 1

        # Thread pool.
        # Blocks other threads (more than the set limit).
        pool.acquire(blocking=True)
        # Create a new thread.
        # Pass each URL (i.e. u parameter) to the worker function.
        t = threading.Thread(target=worker, args=(MEDIAWIKI_API_ENDPOINT+urllib.quote(article['title'])+'/'+str(article['rev_id']), article, iteration_number))

        # Start the newly create thread.
        t.start()
    seconds = time.clock() - start
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    print "Total time: %d:%02d:%02d" % (h, m, s)
开发者ID:linksuccess,项目名称:linksuccess,代码行数:34,代码来源:crawler.py

示例7: learn

    def learn(self, filename):
        """Load and learn the contents of the specified AIML file.

        If filename includes wildcard characters, all matching files
        will be loaded and learned.

        """
        for f in glob.glob(filename):
            if self._verboseMode: print("Loading %s..." % f, end=' ')
            start = time.clock()
            # Load and parse the AIML file.
            parser = AimlParser.create_parser()
            handler = parser.getContentHandler()
            handler.setEncoding(self._textEncoding)
            try:
                parser.parse(f)
            except xml.sax.SAXParseException as msg:
                err = "\nFATAL PARSE ERROR in file %s:\n%s\n" % (f, msg)
                sys.stderr.write(err)
                continue
            # store the pattern/template pairs in the PatternMgr.
            for key, tem in list(handler.categories.items()):
                self._brain.add(key, tem)
            # Parsing was successful.
            if self._verboseMode:
                print("done (%.2f seconds)" % (time.clock() - start))
开发者ID:REDxEYE,项目名称:VK_BOT,代码行数:26,代码来源:Kernel.py

示例8: run

 def run(self):
     global q
     while(time.clock() < 10):
         if(self.nextTime < time.clock() and not q.empty()):
             f = q.get()
             print("Removing " + f)
             self.nextTime += random.random()*2
开发者ID:CabbageHead-360,项目名称:Learning-Algorighms,代码行数:7,代码来源:Example2.py

示例9: executeOneSetting

def executeOneSetting(tensor, density, roundId, para):
    logger.info('density=%.2f, %2d-round starts.'%(density, roundId + 1))
    (numUser, numService, numTime) = tensor.shape

    # remove the entries of data to generate trainTensor and testTensor
    (trainTensor, testTensor) = evallib.removeTensor(tensor, density, roundId, para) 

    # invocation to the prediction function
    startTime = time.clock() # to record the running time for one round             
    predictedTensor = Average.predict(trainTensor, para) 
    runningTime = float(time.clock() - startTime) / numTime

    # evaluate the prediction error 
    for sliceId in xrange(numTime):
        testMatrix = testTensor[:, :, sliceId]
        predictedMatrix = predictedTensor[:, :, sliceId]
        (testVecX, testVecY) = np.where(testMatrix)
        testVec = testMatrix[testVecX, testVecY]
        predVec = predictedMatrix[testVecX, testVecY]
        evalResult = evallib.errMetric(testVec, predVec, para['metrics'])        
        result = (evalResult, runningTime)

        # dump the result at each density
        outFile = '%s%s_%s_result_%02d_%.2f_round%02d.tmp'%(para['outPath'], 
            para['dataName'], para['dataType'], sliceId + 1, density, roundId + 1)
        evallib.dumpresult(outFile, result)
        
    logger.info('density=%.2f, %2d-round done.'%(density, roundId + 1))
    logger.info('----------------------------------------------')
开发者ID:SaravanapriyaM,项目名称:WS-DREAM,代码行数:29,代码来源:evaluator.py

示例10: SaveData

	def SaveData (self, fname, verbose = True):

		if (verbose):
			print ("  Saving measurement to %s ... " % fname)

		start = time.clock()

		f = h5py.File(fname, 'w')

		f['data_r'] = np.squeeze(np.real(self.data).transpose())
		f['data_i'] = np.squeeze(np.imag(self.data).transpose())

		if (self.noise != 0):
			f['noise_r'] = np.squeeze(np.real(self.noise).transpose())
			f['noise_i'] = np.squeeze(np.imag(self.noise).transpose())
		
		if (self.acs != 0):
			f['acs_r'] = np.squeeze(np.real(self.acs).transpose())
			f['acs_i'] = np.squeeze(np.imag(self.acs).transpose())
		
		if (self.sync.any() != 0):
                        f['sync']  = self.sync.transpose()

		f.close()

		if (verbose):
			print '    ... saved in %(time).1f s.\n' % {"time": time.clock()-start}

		return
开发者ID:kvahed,项目名称:PyRawReader,代码行数:29,代码来源:rawparser.py

示例11: demo

def demo(print_times=True, print_grammar=True,
         print_trees=True, print_sentence=True,
         trace=1,
         parser=FeatureChartParser,
         sent='I saw John with a dog with my cookie'):
    import sys, time
    print()
    grammar = demo_grammar()
    if print_grammar:
        print(grammar)
        print()
    print("*", parser.__name__)
    if print_sentence:
        print("Sentence:", sent)
    tokens = sent.split()
    t = time.clock()
    cp = parser(grammar, trace=trace)
    chart = cp.chart_parse(tokens)
    trees = list(chart.parses(grammar.start()))
    if print_times:
        print("Time: %s" % (time.clock() - t))
    if print_trees:
        for tree in trees: print(tree)
    else:
        print("Nr trees:", len(trees))
开发者ID:Weiming-Hu,项目名称:text-based-six-degree,代码行数:25,代码来源:featurechart.py

示例12: printOutput

def printOutput(config, outputDirName, varDF):
    '''Output run statistics and variant details to the specified output directory.'''

    startTime = time.clock()
    print("\n=== Writing output files to {0}/ ===".format(outputDirName))
    ow = output.Writer()
    # identify formats ending in 'xlsx' as the "excel formats," requiring XlsxWriter
    excel_formats = [ plugin_name for plugin_name,file_name in ow.file_names.items() if os.path.splitext(file_name)[1]==".xlsx" ]
    if "all" in config.outputFormats:
        # replace output type 'all' with a lsit of all supported output types
        #    and remove 'all' and 'default' to prevent recursive execution of the modules
        config.outputFormats = ow.supported_formats.keys()
        config.outputFormats.remove('all')
        config.outputFormats.remove('default')
        if 'xlsxwriter' not in sys.modules and excel_formats:
            # if xlsxwriter is not present and the user selected excel output formats, remove excel formats from output formats
            config.outputFormats = [ x for x in config.outputFormats if x not in excel_formats ]
            throwWarning("xlsxwriter module not found; Excel outputs disabled")

    for format in config.outputFormats:
        ow.write(varDF,format,outputDirName,config)

    totalTime = time.clock() - startTime
    print("\tTime to write: {0:02d}:{1:02d}".format(int(totalTime/60), int(totalTime % 60)))
    return 0
开发者ID:blachlylab,项目名称:mucor,代码行数:25,代码来源:mucor.py

示例13: do_effect

    def do_effect(self, can_msg, args):  # read full packet from serial port
        if args.get('action') == 'read':
            can_msg = self.do_read(can_msg)
        elif args.get('action') == 'write':
            # KOSTYL: workaround for BMW e90 bus
            if self._restart and self._run and (time.clock() - self.last) >= self.act_time:
                self.dev_write(0, "O")
                self.last = time.clock()
            self.do_write(can_msg)
        else:
            self.dprint(1, 'Command ' + args['action'] + ' not implemented 8(')


        """
        if self._restart:
                if self.wait_for and can_msg.debugData and can_msg.debugText['text'][0] == "F" and len(can_msg.debugText['text']) > 2:
                    error = int(can_msg.debugText['text'][1:3],16)
                    self.dprint(1,"BUS ERROR:" + hex(error))
                    if error & 8: # Fix for BMW CAN where it could be overloaded
                       self.dev_write(0, "C")
                       time.sleep(0.4)
                       self.dev_write(0, "O")
                       can_msg.debugText['do_not_send'] = True
                    else:
                       can_msg.debugText['please_send'] = True
                    self.wait_for = False

                elif time.clock() - self.last >= self.act_time and not self.wait_for:
                    self.dev_write(0, "F")
                    self.wait_for = True
                    self.last = time.clock()
        """

        return can_msg
开发者ID:Sts0mrg0,项目名称:CANToolz,代码行数:34,代码来源:hw_USBtin.py

示例14: update

def update(params):
	# Descarga el ZIP
	xbmc.output("[updater.py] update")
	xbmc.output("[updater.py] cwd="+os.getcwd())
	remotefilename = REMOTE_FILE+params.get("version")+".zip"
	localfilename = LOCAL_FILE+params.get("version")+".zip"
	xbmc.output("[updater.py] remotefilename=%s" % remotefilename)
	xbmc.output("[updater.py] localfilename=%s" % localfilename)
	xbmc.output("[updater.py] descarga fichero...")
	inicio = time.clock()
	urllib.urlretrieve(remotefilename,localfilename)
	fin = time.clock()
	xbmc.output("[updater.py] Descargado en %d segundos " % (fin-inicio+1))
	
	# Lo descomprime
	xbmc.output("[updater.py] descomprime fichero...")
	import ziptools
	unzipper = ziptools.ziptools()
	destpathname = DESTINATION_FOLDER
	xbmc.output("[updater.py] destpathname=%s" % destpathname)
	unzipper.extract(localfilename,destpathname)
	
	# Borra el zip descargado
	xbmc.output("[updater.py] borra fichero...")
	os.remove(localfilename)
开发者ID:HackJoues,项目名称:pelisalacarta-personal-fork,代码行数:25,代码来源:updater.py

示例15: run

def run(test):
    global test_name
    test_name = test

    t0 = time.clock()
    msg("setting up supervisor")
    exe = test + '.exe'
    proc = Popen(exe, bufsize=1<<20 , stdin=PIPE, stdout=PIPE, stderr=PIPE)
    done = multiprocessing.Value(ctypes.c_bool)
    queue = multiprocessing.Queue(maxsize=5)#(maxsize=1024)
    workers = []
    for n in range(NUM_WORKERS):
        worker = multiprocessing.Process(name='Worker-' + str(n + 1),
                                         target=init_worker,
                                         args=[test, MAILBOX, queue, done])
        workers.append(worker)
        child_processes.append(worker)
    for worker in workers:
        worker.start()
    msg("running test")
    interact(proc, queue)
    with done.get_lock():
        done.value = True
    for worker in workers:
        worker.join()
    msg("python is done")
    assert queue.empty(), "did not validate everything"
    dt = time.clock() - t0
    msg("took", round(dt, 3), "seconds")
开发者ID:EricIO,项目名称:rust,代码行数:29,代码来源:runtests.py


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