下载

1下载券

加入VIP
  • 专属下载券
  • 上传内容扩展
  • 资料优先审核
  • 免费资料无限下载

上传资料

关闭

关闭

关闭

封号提示

内容

首页 ManagingMemory

ManagingMemory.pdf

ManagingMemory

hbwang85
2013-06-26 0人阅读 举报 0 0 0 暂无简介

简介:本文档为《ManagingMemorypdf》,可适用于IT/计算机领域

MemoryUsagePerformanceGuidelinesContentsIntroductionOrganizationofThisDocumentAbouttheVirtualMemorySystemAboutVirtualMemoryDetailsoftheVirtualMemorySystemWiredMemoryPageListsintheKernelPagingOutProcessPagingInProcessTipsforAllocatingMemoryTipsforImprovingMemoryRelatedPerformanceDeferYourMemoryAllocationsInitializeMemoryBlocksEfficientlyReuseTemporaryMemoryBuffersFreeUnusedMemoryMemoryAllocationTechniquesAllocatingObjectsAllocatingSmallMemoryBlocksUsingMallocAllocatingLargeMemoryBlocksusingMallocAllocatingMemoryinBatchesAllocatingSharedMemoryUsingMallocMemoryZonesCopyingMemoryUsingMallocCopyingMemoryDirectlyDelayingMemoryCopyOperationsCopyingSmallAmountsofDataCopyingDatatoVideoRAMRespondingtoLowMemoryWarningsiniOSCachingandPurgeableMemoryOverviewofCachingWhyUseCaching|©,AppleIncAllRightsReservedProblemsCachingCanCauseSolutionsUsingPurgeableMemoryAdvantagesofUsingPurgeableMemoryHowtoImplementPurgeableMemoryPurgeableMemoryandNSCacheSomeWarningsAboutPurgeableMemoryWhentoUsePurgeableMemoryTrackingMemoryUsageTrackingAllocationsWithInstrumentsAnalyzingMemoryAllocationswiththeObjectAllocInstrumentAnalyzingSharedMemoryUsageAnalyzingDatafromtheMemoryMonitorInstrumentTrackingMemoryAllocationsWithmallochistoryExaminingMemoryWiththeheapToolFindingMemoryLeaksFindingLeaksUsingInstrumentsUsingtheleaksToolTipsforImprovingLeakDetectionEnablingtheMallocDebuggingFeaturesEnablingGuardMallocConfiguringtheMallocEnvironmentVariablesDetectingDoubleFreedMemoryDetectingHeapCorruptionDetectingMemorySmashingBugsViewingVirtualMemoryUsageViewingVirtualMemoryStatisticsViewingMachOCodePagesViewingVirtualMemoryRegionsSampleOutputFromvmmapInterpretingvmmap’sOutputDocumentRevisionHistoryIndex|©,AppleIncAllRightsReservedTablesandListingsAbouttheVirtualMemorySystemTableFieldsoftheVMobjectTableWiredmemorygeneratedbyuserlevelsoftwareTipsforAllocatingMemoryListingLazyallocationofmemorythroughanaccessorListingAllocatingmemorywithvmallocateEnablingtheMallocDebuggingFeaturesTableMallocenvironmentvariablesViewingVirtualMemoryUsageTableColumndescriptionsforvmmapListingOutputofvmstattoolListingPartialoutputofpagestufftoolListingTypicaloutputofvmmap|©,AppleIncAllRightsReservedMemoryisanimportantsystemresourcethatallprogramsuseProgramsmustbeloadedintomemorybeforetheycanrunand,whilerunning,theyallocateadditionalmemory(bothexplicitlyandimplicitly)tostoreandmanipulateprogramleveldataMakingroominmemoryforaprogram’scodeanddatarequirestimeandresourcesandthereforeaffecttheoverallperformanceofthesystemAlthoughyoucannotavoidusingmemoryaltogether,therearewaystominimizetheimpactyourmemoryusagehasontherestofthesystemThisdocumentprovidesbackgroundinformationaboutthememorysystemsofOSXandiOSandhowyouusethemefficientlyYoucanusethisinformationtotuneyourprogram’smemoryusagebyensuringyouareallocatingtherightamountofmemoryattherighttimeThisdocumentalsoprovidestipsonhowtodetectmemoryrelatedperformanceissuesinyourprogramOrganizationofThisDocumentThisprogrammingtopicincludesthefollowingarticles:●“AbouttheVirtualMemorySystem”(page)introducestheterminologyandprovidesahighleveloverviewofthevirtualmemorysystemsofOSXandiOS●“TipsforAllocatingMemory”(page)describesthebesttechniquesforallocating,initializing,andcopyingmemoryItalsodescribestheproperwaystorespondtolowmemorynotificationsiniOS●“CachingandPurgeableMemory”(page)discussesthebenefitsofcaching,andhowtoavoidsomeoftheproblemsthatcanarisefromimplementingcachesItalsodetailstheadvantagesofimplementingpurgeablememoryintoacachingsystemandhowtosuccessfullyimplementthisbeneficialtechnology●“TrackingMemoryUsage”(page)describesthetoolsandtechniquesforanalyzingyourapplication’smemoryusage●“FindingMemoryLeaks”(page)describesthetoolsandtechniquesforfindingmemoryleaksinyourapplication●“EnablingtheMallocDebuggingFeatures”(page)describestheenvironmentvariablesusedtoenablemallochistoryloggingYoumustsetsomeofthesevariablesbeforeusingsomeofthememoryanalysistools●“ViewingVirtualMemoryUsage”(page)describesthetoolsandtechniquesforanalyzingyourapplication’sinmemoryfootprint|©,AppleIncAllRightsReservedIntroductionEfficientmemorymanagementisanimportantaspectofwritinghighperformancecodeinbothOSXandiOSMinimizingmemoryusagenotonlydecreasesyourapplication’smemoryfootprint,itcanalsoreducetheamountofCPUtimeitconsumesInordertoproperlytuneyourcodethough,youneedtounderstandsomethingabouthowtheunderlyingsystemmanagesmemoryBothOSXandiOSincludeafullyintegratedvirtualmemorysystemthatyoucannotturnoffitisalwaysonBothsystemsalsoprovideuptogigabytesofaddressablespaceperbitprocessInaddition,OSXprovidesapproximatelyexabytesofaddressablespaceforbitprocessesEvenforcomputersthathaveormoregigabytesofRAMavailable,thesystemrarelydedicatesthismuchRAMtoasingleprocessTogiveprocessesaccesstotheirentiregigabyteorexabyteaddressspace,OSXusestheharddisktoholddatathatisnotcurrentlyinuseAsmemorygetsfull,sectionsofmemorythatarenotbeingusedarewrittentodisktomakeroomfordatathatisneedednowTheportionofthediskthatstorestheunuseddataisknownasthebackingstorebecauseitprovidesthebackupstorageformainmemoryAlthoughOSXsupportsabackingstore,iOSdoesnotIniPhoneapplications,readonlydatathatisalreadyonthedisk(suchascodepages)issimplyremovedfrommemoryandreloadedfromdiskasneededWritabledataisneverremovedfrommemorybytheoperatingsystemInstead,iftheamountoffreememorydropsbelowacertainthreshold,thesystemaskstherunningapplicationstofreeupmemoryvoluntarilytomakeroomfornewdataApplicationsthatfailtofreeupenoughmemoryareterminatedNote:UnlikemostUNIXbasedoperatingsystems,OSXdoesnotuseapreallocateddiskpartitionforthebackingstoreInstead,itusesalloftheavailablespaceonthemachine’sbootpartitionThefollowingsectionsintroduceterminologyandprovideabriefoverviewofthevirtualmemorysystemusedinbothOSXandiOSFormoredetailedinformationonhowthevirtualmemorysystemworks,seeKernelProgrammingGuideAboutVirtualMemoryVirtualmemoryallowsanoperatingsystemtoescapethelimitationsofphysicalRAMThevirtualmemorymanagercreatesalogicaladdressspace(or“virtual”addressspace)foreachprocessanddividesitupintouniformlysizedchunksofmemorycalledpagesTheprocessoranditsmemorymanagementunit(MMU)|©,AppleIncAllRightsReservedAbouttheVirtualMemorySystemmaintainapagetabletomappagesintheprogram’slogicaladdressspacetohardwareaddressesinthecomputer’sRAMWhenaprogram’scodeaccessesanaddressinmemory,theMMUusesthepagetabletotranslatethespecifiedlogicaladdressintotheactualhardwarememoryaddressThistranslationoccursautomaticallyandistransparenttotherunningapplicationAsfarasaprogramisconcerned,addressesinitslogicaladdressspacearealwaysavailableHowever,ifanapplicationaccessesanaddressonamemorypagethatisnotcurrentlyinphysicalRAM,apagefaultoccursWhenthathappens,thevirtualmemorysysteminvokesaspecialpagefaulthandlertorespondtothefaultimmediatelyThepagefaulthandlerstopsthecurrentlyexecutingcode,locatesafreepageofphysicalmemory,loadsthepagecontainingtheneededdatafromdisk,updatesthepagetable,andthenreturnscontroltotheprogram’scode,whichcanthenaccessthememoryaddressnormallyThisprocessisknownaspagingIftherearenofreepagesavailableinphysicalmemory,thehandlermustfirstreleaseanexistingpagetomakeroomforthenewpageHowthesystemreleasepagesdependsontheplatformInOSX,thevirtualmemorysystemoftenwritespagestothebackingstoreThebackingstoreisadiskbasedrepositorycontainingacopyofthememorypagesusedbyagivenprocessMovingdatafromphysicalmemorytothebackingstoreiscalledpagingout(or“swappingout”)movingdatafromthebackingstorebackintophysicalmemoryiscalledpagingin(or“swappingin”)IniOS,thereisnobackingstoreandsopagesareareneverpagedouttodisk,butreadonlypagesarestillbepagedinfromdiskasneededInbothOSXandiOS,thesizeofapageiskilobytesThus,everytimeapagefaultoccurs,thesystemreadskilobytesfromdiskDiskthrashingcanoccurwhenthesystemspendsadisproportionateamountoftimehandlingpagefaultsandreadingandwritingpages,ratherthanexecutingcodeforaprogramPagingofanykind,anddiskthrashinginparticular,affectsperformancenegativelybecauseitforcesthesystemtospendalotoftimereadingandwritingtodiskReadingapageinfromthebackingstoretakesasignificantamountoftimeandismuchslowerthanreadingdirectlyfromRAMIfthesystemhastowriteapagetodiskbeforeitcanreadanotherpagefromdisk,theperformanceimpactisevenworseDetailsoftheVirtualMemorySystemThelogicaladdressspaceofaprocessconsistsofmappedregionsofmemoryEachmappedmemoryregioncontainsaknownnumberofvirtualmemorypagesEachregionhasspecificattributescontrollingsuchthingsasinheritance(portionsoftheregionmaybemappedfrom“parent”regions),writeprotection,andwhetheritiswired(thatis,itcannotbepagedout)Becauseregionscontainaknownnumberofpages,theyarepagealigned,meaningthestartingaddressoftheregionisalsothestartingaddressofapageandtheendingaddressalsodefinestheendofapageThekernelassociatesaVMobjectwitheachregionofthelogicaladdressspaceThekernelusesVMobjectstotrackandmanagetheresidentandnonresidentpagesoftheassociatedregionsAregioncanmaptopartofthebackingstoreortoamemorymappedfileinthefilesystemEachVMobjectcontainsamapthatAbouttheVirtualMemorySystemDetailsoftheVirtualMemorySystem|©,AppleIncAllRightsReservedassociatesregionswitheitherthedefaultpagerorthevnodepagerThedefaultpagerisasystemmanagerthatmanagesthenonresidentvirtualmemorypagesinthebackingstoreandfetchesthosepageswhenrequestedThevnodepagerimplementsmemorymappedfileaccessThevnodepagerusesthepagingmechanismtoprovideawindowdirectlyintoafileThismechanismletsyoureadandwriteportionsofthefileasiftheywerelocatedinmemoryInadditiontomappingregionstoeitherthedefaultorvnodepager,aVMobjectmayalsomapregionstoanotherVMobjectThekernelusesthisselfreferencingtechniquetoimplementcopyonwriteregionsCopyonwriteregionsallowdifferentprocesses(ormultipleblocksofcodewithinaprocess)toshareapageaslongasnoneofthemwritetothatpageWhenaprocessattemptstowritetothepage,acopyofthepageiscreatedinthelogicaladdressspaceoftheprocessdoingthewritingFromthatpointforward,thewritingprocessmaintainsitsownseparatecopyofthepage,whichitcanwritetoatanytimeCopyonwriteregionsletthesystemsharelargequantitiesofdataefficientlyinmemorywhilestilllettingprocessesmanipulatethosepagesdirectly(andsafely)ifneededThesetypesofregionsaremostcommonlyusedforthedatapagesloadedfromsystemframeworksEachVMobjectcontainsseveralfields,asshowninTableTableFieldsoftheVMobjectDescriptionFieldAlistofthepagesofthisregionthatarecurrentlyresidentinphysicalmemoryResidentpagesThesizeoftheregion,inbytesSizeThepagerresponsiblefortrackingandhandlingthepagesofthisregioninbackingstorePagerUsedforcopyonwriteoptimizationsShadowUsedforcopyonwriteoptimizationsCopyFlagsindicatingthestateofvariousimplementationdetailsAttributesIftheVMobjectisinvolvedinacopyonwrite(vmcopy)operation,theshadowandcopyfieldsmaypointtootherVMobjectsOtherwisebothfieldsareusuallyAbouttheVirtualMemorySystemDetailsoftheVirtualMemorySystem|©,AppleIncAllRightsReservedWiredMemoryWiredmemory(alsocalledresidentmemory)storeskernelcodeanddatastructuresthatmustneverbepagedouttodiskApplications,frameworks,andotheruserlevelsoftwarecannotallocatewiredmemoryHowever,theycanaffecthowmuchwiredmemoryexistsatanytimeForexample,anapplicationthatcreatesthreadsandportsimplicitlyallocateswiredmemoryfortherequiredkernelresourcesthatareassociatedwiththemTablelistssomeofthewiredmemorycostsforapplicationgeneratedentitiesTableWiredmemorygeneratedbyuserlevelsoftwareWiredMemoryUsedbyKernelResourcekilobytesProcessblockedinacontinuationkilobytesblockedkilobytesThreadbytesMachportbytesMappingkilobytesplusbytesforeachtaskthatusesitLibrarybytesMemoryregionNote:ThesemeasurementsmaychangewitheachnewreleaseoftheoperatingsystemTheyareprovidedheretogiveyouaroughestimateoftherelativecostofsystemresourceusageAsyoucansee,everythread,process,andlibrarycontributestotheresidentfootprintofthesystemInadditiontoyourapplicationusingwiredmemory,however,thekernelitselfrequireswiredmemoryforthefollowingentities:●VMobjects●thevirtualmemorybuffercache●IObuffercaches●driversWireddatastructuresarealsoassociatedwiththephysicalpageandmaptablesusedtostorevirtualmemorymappinginformation,BothoftheseentitiesscalewiththeamountofavailablephysicalmemoryConsequently,whenyouaddmemorytoasystem,theamountofwiredmemoryincreasesevenifnothingelsechangesWhenacomputerisfirstbootedintotheFinder,withnootherapplicationsrunning,wiredmemorycanconsumeapproximatelymegabytesofamegabytesystemandmegabytesofamegabytesystemAbouttheVirtualMemorySystemWiredMemory|©,AppleIncAllRightsReservedWiredmemorypagesarenotimmediatelymovedbacktothefreelistwhentheybecomeinvalidInsteadtheyare“garbagecollected”whenthefreepagecountfallsbelowthethresholdthattriggerspageouteventsPageListsintheKernelThekernelmaintainsandqueriesthreesystemwidelistsofphysicalmemorypages:●Theactivelistcontainspagesthatarecurrentlymappedintomemoryandhavebeenrecentlyaccessed●TheinactivelistcontainspagesthatarecurrentlyresidentinphysicalmemorybuthavenotbeenaccessedrecentlyThesepagescontainvaliddatabutmayberemovedfrommemoryatanytime●ThefreelistcontainspagesofphysicalmemorythatarenotassociatedwithanyaddressspaceofVMobjectThesepagesareavailableforimmediateusebyanyprocessthatneedsthemWhenthenumberofpagesonthefreelistfallsbelowathreshold(determinedbythesizeofphysicalmemory),thepagerattemptstobalancethequeuesItdoesthisbypullingpagesfromtheinactivelistIfapagehasbeenaccessedrecently,itisreactivatedandplacedontheendoftheactivelistInOSX,ifaninactivepagecontainsdatathathasnotbeenwrittentothebackingstorerecently,itscontentsmustbepagedouttodiskbeforeitcanbeplacedonthefreelist(IniOS,modifiedbutinactivepagesmustremaininmemoryandbecleanedupbytheapplicationthatownsthem)Ifaninactivepagehasnotbeenmodifiedandisnotpermanentlyresident(wired),itisstolen(anycurrentvirtualmappingstoitaredestroyed)andaddedtothefreelistOncethefreelistsizeexceedsthetargetthreshold,thepagerrestsThekernelmovespagesfromtheactivelisttotheinactivelistiftheyarenotaccesseditmovespagesfromtheinactivelisttotheactivelistonasoftfault(see“PagingInProcess”(page))Whenvirtualpagesareswappedout,theassociatedphysicalpagesareplacedinthefreelistAlso,whenprocessesexplicitlyfreememory,thekernelmovestheaffectedpagestothefreelistPagingOutProcessInOSX,whenthenumberofpagesinthefreelistdipsbelowacomputedthreshold,thekernelreclaimsphysicalpagesforthefreelistbyswappinginactivepagesoutofmemoryTodothis,thekerneliteratesallresidentpagesintheactiveandinactivelists,performingthefollowingsteps:Ifapageintheactivelistisnotrecentlytouched,itismovedtotheinactivelistIfapageintheinactivelistisnotrecentlytouched,thekernelfindsthepage’sVMobjectIftheVMobjecthasneverbeenpagedbefore,thekernelcallsaninitializationroutinethatcreatesandassignsadefaultpagerobjectAbouttheVirtualMemorySystemPageListsintheKernel|©,AppleIncAllRightsReservedTheVMobject’sdefaultpagerattemptstowritethepageouttothebackingstoreIfthepagersucceeds,thekernelfreesthephysicalmemoryoccupiedbythepageandmovesthepagefromtheinactivetothefreelistNote:IniOS,thekerneldoesnotwritepagesouttoabackingstoreWhentheamountoffreememorydipsbelowthecomputedthreshold,thekernelflushespagesthatareinactiveandunmodifiedandmayalsoasktherunningapplicationtofreeupmemorydirectlyFormoreinformationonrespondingtothesenotifications,see“RespondingtoLowMemoryWarningsiniOS”(page)PagingInProcessThefinalphaseofvirtualmemorymanagementmovespagesintophysicalmemory,eitherfromthebackingstoreorfromthefilecontainingthepagedataAmemoryaccessfaultinitiatesthepageinprocessAmemoryaccessfaultoccurswhencodetriestoaccessdataatavirtualaddressthatisnotmappedtophysicalmemoryTherearetwokindsoffaults:●Asoftfaultoccurswhenthepageofthereferencedaddressisresidentinphysicalmemorybutiscurrentlynotmappedintotheaddressspaceofthisprocess●Ahardfaultoccurswhenthepageofthereferencedaddressisnotinphysicalmemorybutisswappedouttobackingstore(orisavailablefromamappedfile)ThisiswhatistypicallyknownasapagefaultWhenanytypeoffaultoccurs,thekernellocatesthemapentryandVMobjectfortheaccessedregionThekernelthengoesthroughtheVMobject’slistofresidentpagesIfthedesiredpageisinthelistofresidentpag

用户评价(0)

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

评分:

/47

VIP

意见
反馈

免费
邮箱