Is there a way to measure the time taken this algorithm takes ...

文章推薦指數: 80 %
投票人數:10人

Beware : "by default, timeit() temporarily turns off garbage collection during the timing. The advantage of this approach is that it makes ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams IsthereawaytomeasurethetimetakenthisalgorithmtakestosolvethisSodukuPuzzle? AskQuestion Asked 1year,6monthsago Modified 3monthsago Viewed 83times 0 IhavecodetosolveasudokupuzzleusingtheBacktrackingalgorithm.IwanttofindouthowlongtheBacktrackingalgorithmtakestosolvethesudokupuzzleinsecondsormilliseceondsusingthepythonlanguage. Mycodeis ''' fromtabulateimporttabulate importtimeit #A9x9matrixwhichrepresentsoursudokusolver sudoku_board=[ [0,0,0,0,0,0,2,0,0], [0,8,0,0,0,7,0,9,0], [6,0,2,0,0,0,5,0,0], [0,7,0,0,6,0,0,0,0], [0,0,0,9,0,1,0,0,0], [0,0,0,0,2,0,0,4,0], [0,0,5,0,0,0,6,0,3], [0,9,0,4,0,0,0,7,0], [0,0,6,0,0,0,0,0,0] ] #Displaytheboard defdisplay_board(sudoku_board): print(tabulate(sudoku_board,tablefmt='fancy_grid')) #LookforanunassignedcellifitexistsreturnrowandcolvalueselsereturnFalse defempty_cells_exist(): foriinrange(9): forjinrange(9): ifsudoku_board[i][j]==0: return[i,j] returnFalse #Isourchoicegoodornot? defvalid_number_check(num,i,j): #Checkingvertically forrowinrange(9): ifsudoku_board[row][j]==num: returnFalse #Checkinghorizontally forcolinrange(9): ifsudoku_board[i][col]==num: returnFalse #Checkinthe3x3gird/box grid_row=(i//3)*3 grid_col=(j//3)*3 foriinrange(3): forjinrange(3): ifsudoku_board[grid_row+i][grid_col+j]==num: returnFalse #Oncealltestsarepassedreturntrue returnTrue #Solver defsolver(): cells_exist=empty_cells_exist() ifnotcells_exist: returnTrue i,j=cells_exist[0],cells_exist[1] fornuminrange(1,10): ifvalid_number_check(num,i,j): sudoku_board[i][j]=num #Backtracking(checkingthenextstep) ifsolver(): returnTrue else: sudoku_board[i][j]=0 #Falseifnothing(1through9)yieldan"acceptedanswer" returnFalse display_board(sudoku_board) ifsolver(): display_board(sudoku_board) else: print("nosolutionavailable") if__name__=="__main__": print(timeit.timeit(solver,number=10000)) ,,, AsyoucanseeIhaveattemptedtotimethesolverfunctionbutitreturnsanumberlike0.07027392299999846whichisnotoftheformatrequired.Iamrequiringittobeinaclearreadableformatforhumanstoundestand.Suchasminutesandsecondsformat. pythonalgorithmtimebacktrackingsudoku Share Follow editedApr22,2021at16:19 ZoestandswithUkraine♦ 25.7k1818goldbadges114114silverbadges146146bronzebadges askedMar15,2021at10:35 PaulieWalnutsPaulieWalnuts 3366bronzebadges 1 Asyoucanreaditinthedoc,itismeasuredinseconds.See:docs.python.org/3/library/timeit.html.Isitconsistentwhithhowlongyouthinkittakes?Beware:"bydefault,timeit()temporarilyturnsoffgarbagecollectionduringthetiming.Theadvantageofthisapproachisthatitmakesindependenttimingsmorecomparable.ThedisadvantageisthatGCmaybeanimportantcomponentoftheperformanceofthefunctionbeingmeasured.Ifso,GCcanbere-enabledasthefirststatementinthesetupstring."Seelinkfordetails. – Malo Mar15,2021at15:43 Addacomment  |  2Answers 2 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 2 ForthisIusuallyusedatetime.datetime.now: >>>importdatetime >>>begin=datetime.datetime.now() >>>begin datetime.datetime(2021,3,15,...,40,14,560666) >>>end=datetime.datetime.now() >>>end-begin datetime.timedelta(seconds=10,microseconds=530067) >>>str(_) '0:00:10.530067'#thenicerepresentation Orconstructthetimedeltaobjectyourself: >>>datetime.timedelta(seconds=0.07027392299999846) datetime.timedelta(microseconds=70274) >>>str(_) '0:00:00.070274' Soyourcodecouldlooklikethis: dt=timeit.timeit(solver,number=10000) print(datetime.timedelta(seconds=dt)) Share Follow answeredMar15,2021at10:41 ForceBruForceBru 42.2k1010goldbadges6565silverbadges9191bronzebadges 0 Addacomment  |  0 youcanmesuretimetakenusingmoduletime importtime time1=time.time() #code time2=time.time() time=time2-time1 print(f"timetaken{time}seconds") Share Follow editedJun19at22:21 answeredApr1,2021at19:27 Fun_Dan3Fun_Dan3 1511silverbadge77bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonalgorithmtimebacktrackingsudokuoraskyourownquestion. TheOverflowBlog MissedourFlowStateconference?Catchuponallthesessions HowtoearnamillionreputationonStackOverflow:beofservicetoothers FeaturedonMeta BookmarkshaveevolvedintoSaves Inboximprovements:markingnotificationsasread/unread,andafiltered... Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... CollectivesUpdate:RecognizedMembers,Articles,andGitLab Related 613 HowdoImeasureexecutiontimeofacommandontheWindowscommandline? 715 IsthereaportablewaytogetthecurrentusernameinPython? 1025 HowcanIfindthetimecomplexityofanalgorithm? 2 Sudokusolverwithrecursionandbacktracking 0 Backtrackinginsudokusolverfailing 0 AbortTrapError:6-whereisitcomingfrom?-Sudokusolver 1 recursivebacktrackingalgorithmthatcountsallsolutions HotNetworkQuestions Howtotranslate"Hewhocan,must"? Onlinehomeworksystemsforordinarydifferentialequations Alignenvironmentwithmultipleseparatedvalues Traditionally,andcurrently,whatstopshumanvotecountersfromalteringballotstomakethem'Spoilt/Invalidvotes? Howdocompilersworkinalanguagethatdoesn'tallowrecursion? Idon'tunderstandif"per"meaningexactamountforeachunitordoesitmean"onaverage" GradientDescentandLearningRate Whyarefighterjetssoloudwhendoingslowflight? WhatFundamentalForcedoappliedforces(kickingaball,pushinganobject)fallunder? What'sthereasonthatwearetoldthatRachavwasazonah? Whydoesthepresenceoficeandorganics(carbon,ammonia,water,etc)matterinspaceexploration? transparentimageshaveawhiteglowonsomeedges Performsameoperationalongdimensionofanarray HowtogetridofUbuntuProadvertisementwhenupdatingapt? Howdotamalescook? Grammarlysaysthatstarting"LikePearlwashesitantto..."with"Like"isfine,butmyparentsaysitisgrammaticallyincorrect Aretheseusesofinfinitivephrasessyntacticmodifiersorsyntacticcomplements,andofwhat? DoesMageHandworkwithSparetheDying? WhyamigettingasortwhenIhaveanindex? WhydopeopleinsistonusingTikzwhentheycanusesimplerdrawingtools? Invertingstring-basedbinarynumberinonelineinPython ApplicabilityofDataProtectionLawsWhenTalkingtoaLawyer Whattranslation/versionoftheBiblewouldChaucerhaveread? ElectronicCircuitsforSafeInitiationofPyrotechnics? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?