关闭

关闭

关闭

封号提示

内容

首页 ManagingMemory

ManagingMemory.pdf

ManagingMemory

hbwang85 2013-06-26 评分 0 浏览量 0 0 0 0 暂无简介 简介 举报

简介:本文档为《ManagingMemorypdf》,可适用于IT/计算机领域,主题内容包含MemoryUsagePerformanceGuidelinesContentsIntroductionOrganizationofThisDocu符等。

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:VMobjectsthevirtualmemorybuffercacheIObuffercachesdriversWireddatastructuresarealsoassociatedwiththephysicalpageandmaptablesusedtostorevirtualmemorymappinginformation,BothoftheseentitiesscalewiththeamountofavailablephysicalmemoryConsequently,whenyouaddmemorytoasystem,theamountofwiredmemoryincreasesevenifnothingelsechangesWhenacomputerisfirstbootedintotheFinder,withnootherapplicationsrunning,wiredmemorycanconsumeapproximatelymegabytesofamegabytesystemandmegabytesofamegabytesystemAbouttheVirtualMemorySystemWiredMemory|,AppleIncAllRightsReservedWiredmemorypagesarenotimmediatelymovedbacktothefreelistwhentheybecomeinvalidInsteadtheyare“garbagecollected”whenthefreepagecountfallsbelowthethresholdthattriggerspageouteventsPageListsintheKernelThekernelmaintainsandqueriesthreesystemwidelistsofphysicalmemorypages:TheactivelistcontainspagesthatarecurrentlymappedintomemoryandhavebeenrecentlyaccessedTheinactivelistcontainspagesthatarecurrentlyresidentinphysicalmemorybuthavenotbeenaccessedrecentlyThesepagescontainvaliddatabutmayberemovedfrommemoryatanytimeThefreelistcontainspagesofphysicalmemorythatarenotassociatedwithanyaddressspaceofVMobjectThesepagesareavailableforimmediateusebyanyprocessthatneedsthemWhenthenumberofpagesonthefreelistfallsbelowathreshold(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:AsoftfaultoccurswhenthepageofthereferencedaddressisresidentinphysicalmemorybutiscurrentlynotmappedintotheaddressspaceofthisprocessAhardfaultoccurswhenthepageofthereferencedaddressisnotinphysicalmemorybutisswappedouttobackingstore(orisavailablefromamappedfile)ThisiswhatistypicallyknownasapagefaultWhenanytypeoffaultoccurs,thekernellocatesthemapentryandVMobjectfortheaccessedregionThekernelthengoesthroughtheVMobject’slistofresidentpagesIfthedesiredpageisinthelistofresidentpag

用户评论(0)

0/200

精彩专题

上传我的资料

每篇奖励 +1积分

资料评分:

/47
1下载券 下载 加入VIP, 送下载券

意见
反馈

立即扫码关注

爱问共享资料微信公众号

返回
顶部

举报
资料