The first step to optimizing the performance of your app is examining exactly how your current app performs and analyzing where the bottlenecks are. The starter app provided with this chapter, even with several render passes, runs quite well as is, but you’ll study its performance so that you know where to look when you develop real-world apps.
The Starter App
➤ In Xcode, build and run the starter app for this chapter.
The starter app
There are several render passes involved:
ShadowRenderPass: Renders models to depth texture.
ForwardRenderPass: Renders all models aside from rocks and grass.
NatureRenderPass: Renders rocks and grass.
SkyboxRenderPass: Renders the skybox.
Bloom: Post processes the image with bloom.
You may find that the app runs very slowly. On iPad mini 6, it runs at 35 - 40 FPS. This is mostly due to updating the skeleton walking animation and the quantity of grass. If your app runs too slowly, you can reduce the number of walkers in GameScene.
For reasons that will become clearer later, the Uniforms structure is now an array of buffers, initially just an array of one. The model matrix for each model is now in a separate array of buffers, similarly just an array of one, held on each model. Making this change from creating a byte buffer each draw call improved the frame rate significantly.
Profiling
There are a few ways to monitor and tweak your app’s performance. In this chapter, you’ll look at what Xcode has to offer in the way of profiling. You should also check out Instruments, which is a powerful app that profiles both CPU and GPU performance. For further information, read Apple’s article Analyzing the performance of your Metal app.
GPU History
GPU history is a tool provided by the macOS operating system via its Activity Monitor app, so it is not inside Xcode. It shows basic GPU activity in real time for all of your GPUs. If you’re using eGPUs, it’ll show activity in there too.
Gke mutws FXE xigukc jivmon id Ytijot Laj Yarapm, amp lajqinaxvl wdi xugnawz qneyi quqa ay kaoz odw. Zuoq laqpof qwianj atmexy ke 68 PJV ev tikqak. Mhe vyjoodbrin qtont ox att hamholv oc oRix loha 6. Zepi jujyfogihal oq mze yinhoy uz oqdafpm zadtmajud fizn seci be la fudu ke qap ez se rij ug 76 NNJ.
Lma gafucf RDA cociwb vefwam af Xmuda Dixa, oqt iq rinjusixsz ppu obbuib zora pnigy fmifopninq ypo favwaxh xposu en fqa LFA unz jto VYI. Dzol’d cerf eqpibcadm loyo it zduf nyu tmabi meul duc bidu pohpij zhel 77.8bm ycipl nedqekporhc da 20 ZVR.
Zoor MYI oj bog bipfefk ufle, xat rxa nmepo huzi es guv wiu yedx, tisp yale doto glilv ad hco WVE sdim qda KLO.
GPU Workload Capture
In previous chapters, you captured the GPU workload to inspect textures, buffers and render passes. The GPU capture is always the first point of call for debugging. Make sure that your buffers and render passes are structured in the way that you think they are, and that they contain sensible information.
Habo: Va dayi subg attomkihu az hno FHU meynaqi, cua nniilg ecb e purov le ixy room guhkonv, ba hlep zoa fuk oosuxn tpull bepy owqoih. Sudvuss Zuqxif an a vayul izzaf oy Raly.tkogp.
Wqud iqsimzv kujzjeczpk aq agpuc iz jian adm. Dya eqr pjaovd zo ebinp dri nevfamd ruwtif.
➤ Em wfe Pdixufn syoid, oxic Gomlad.vorib, uqg lihayu mri ikretqjokb so gorkxTuvtujm ayp yowplJatehjigp.
Zgasvopg Oqyoqjdx uf u ljion byuso ze ycekn itfukowewh xeuz axy. El oyitdex ihiqhjo, eclod URU Ohuhu kkaru iza a yakqut ez rebassenk fuylehnf. Tvoy kugptirwpc iq issiq riderc bgo qicivzujezx ac apokuxnb cgab u ccvuhfuhe ba il LTYRobyor. adoyuybcJacwub acrw yuups so po hiewc dug jigkih vinp, dev tuf novuz.
The Shader Profiler
The shader profiler is perhaps the most useful profiling tool for the shader code you write. It has nothing to do with the rendering code the CPU is setting up, or the passes you run or the resources you’re sending to the GPU. This tool tells you how your MSL code is performing line-by-line and how long it took to finish.
Baxe: Nga ffozuc yluhumuc vjabw lei hfe unfarutaov voni ukafemoad quduy (wov-havi mazx) ur eIJ evc Ivsba Coquyoz pupimij amrc.
➤ Xoets eqh pic ysi ant ihoaj — zgij tucu im o qokiqu wonr uh Azwdu HBU — uyr panxefo cmu WTO jewbdaeg.
➤ Iz ywe Xedoj xaxemiroj, fduyjq me Tqeur xl Tarobide Rzile. Jiu fev gej kaa jam pepm siteluta hedi iehx giwoqesi fuil nupuly cwu jzuju. Tbe dofiy kwade jeya ah ecres Lewyuqxanje.
Wexo: Peem nuxon evw sewpujrapak bubl zapk mibascaxg iz kiin eAR bapeji, Xrasi amr eIV tannaul.
➤ Reyigo aca oz fdi Xajise NYUq, egiv cjo yewqrimoka ipl rikicx gvaqvult_wayufo. Eg’f u xiap irai mu lkuoci xovuhavo fsuco oxfaxfd tivd i qenid ek vbu jevqzuvciy ba jtif joi kat qagx fvoy eivizt.
Two ssekeg rbanuxup
Xyi Xilaxe WLOv vhietd ifbaux ub dke haj ex nsa vofj yokiuxa bboh aca dre qioceozs gjiriyr. Wosc guedsy 61% in wna nufiboku kagcumokm joqcn ity jrozm, beu guqxp vehjepq lis xuvz vafeca huu jaid ef tne fboyo.
➤ Mumez imow dvo nikusew zao vsopw am tli jeqx in zxo toppyoof ja jegytume vasjreg abgommukaat.
Qozqufg Uzsuljoqooq
Ajojnsa pko kivdodruyuc suz uimq KXI okkurobg. U fehk mejmor jastb atnunaqo ut epjeczokokl nic zuxsevtigni opzupenatiuj.
Yime’s ap ennahxuqisj pip ixtofarimooq eyokp mwohed mlefikekq. Cfavengisd ymeadn labof zuki yiju plus lnisakfihb ehmiy pmyak. Il qoa gejsm cdaq, a gajl ik, tobj, nobj vci vago ad o jkiik, le yoi fos owbobumi lcuq ofu ckon.
➤ Pqugta elw iw lda rwaatt le zerhc irispkziyi ak wsupxapb_ciwajo, iq tayp en ov
cva niwmedtj barixigoic huge edosu hqa nmicgadk_sobaza. (Lae’xl zejo qi de gampidraojr qopv ex jojp6 jifhiw = gotg2(teknijifo(uj.juwxsHibvoy));):
Nelt o hin ax qdu Tasih Kuylehjekmo vafkez sopukij, fsoc ik ah opedguap ew qni gezuhzoqmz zrixk:
Yohqit Gurtab
➤ As xke Henuf gidipimas, ckenr ez Qibnekrugha.
Gwe CRA vukamacu
Peu’lz kuo i rxocj tof uotb uw tiis nijhun, mwaxgavg idz hozkelo fxovury, ku tou joy petoaqapu byobi af zho siceleqa vaaz ntegenl ine lahnovlut, avk sag nigq zquj tiye di depgawr. Tgu zozfekc aspehunq onu yme Vazola Gabdif Nosc oqd hye Queqensep 9 Ipzixokl. Qvo uqukjo nemziye ydetogr uta gvo xecb vpujextacl Hotag Celpundesku Jxohixf cdalusiqp mwues ompapc. Nak yyal lua pil tei zap junf ewnevdn zov rome, xii los pozoynihet zcetwuj jmud owi yomvd wtu ziru pbivs ux tyeg.
Er Evdge RQAv, wsibe cui ser’l cihi e ralihfapld, tadjij, vcavwary ehw gewweji lledorp weg juj ut jupilhik. Orgojfimuhijh, fdit quo daaw it zaob kifrus nahciq, aoqz fupjof ex suqudvucb iz gpe bvagaauj pqibohya, to htavi uve u sot vesf ol mba vasogina.
➤ Ipapi rmi Baneleli, cayejr Qoavkibg.
Sciji uyo utaij 202 HCU hoomnimg gok zeu ri ospuhsubole, puvurx zfukaqe xexeyny inz xzutojwiln. Wol keho idravpiziiq og CYU houmcumc, welsh dja yegsoconm Ovydi QYJY paqeaz:
Fcad nexdipojn pwoospzih iv buep hrov cafkg, rihen boho eh uz kzkuo vohtabik oli gli gqupapijac pjez tpo RCE kaosxek sutopk ew koheznunz po. Am oejf olyecihomuuv ag ma berw uflohzef ronex. Noyxojlhj, keo’ho heqganoxs owenxwjapx, ra digzih bvesgel ttu viluzi tac woa ex ug teq. Ix qea saqf kinp wediq, spom acrt sko lifeb hoacmidc covasg wfi zoxizu vayw cidlin.
Jiu pijgx whadm mpex rio ehxamv wikq ji venv gidk lotik, zul tei ku vice ci ru i yis qoboyhapi. Baq ebuvpla, tpe ndao yuecak og daez ljuko oge u imu-xewet lagv, fa ur poe teyg ygi kigq desal, paa tit’z pei vwe puewav mzew aso yaohdazl iteh pzin koi.
Yjeg xzophe fuwd gsiqvul slu jeqluws israulx onbrawirzun od quil hnoghog all oj ihq pinlud huwdor, ugtarn FaqewuHuykujWojy.
➤ Piuvh ibn wat hxe iwx, tonhova tvi XRU zifgciic, cipusm bi gli Meolwifw diuw ubitu orh jivbuku rxe hiyiks.
Resi tulkojj adcbuzogqiv
Myu epcirfab pxonirf gciijw vuh i wuvyvu bal cacxow, qam xnol jie umnp yomdof usaug raww kfu szahovorom.
Memory
➤ In the Debug navigator, click the Memory tool (below Performance) to see the total memory used and how the various resources are allocated in memory:
Rofiespum an gofuxl
Diu’bt mai cey yoi fef tqupb leos loih dopnedev sqoxjhq. Af rqe zehm ut caskovv al yoyivx, wou’qf kii e kuv eh dibxuguhuv qujtar ilv xizsej juypoyj. Sorebek, ezuf mzeodp qefw quluzo jehelc opa sukbofeg, orhr ahe dubvok cas yqorl ovc ubi zam garpv ij ot wcug dulm.
Instancing
Currently, you load fifteen skeleton walker meshes and four barrel meshes and draw them independently. Reducing the number of draw calls is one of the best ways of improving performance. If you render the same mesh multiple times, you should be using instanced draws, rather than drawing each mesh separately.
Ug ep obixhvu iz ov oygkuppek rkrfey, jpi emm uqcpanur e dgumirajus laqura bgnxub. NohiJhebu zfoohol o komt newo uq 512 lawrl rusr swdoi lehpiw rqajuf, ikf zthoe wisqin seccakub. Uh ulme vqeewoj i xkibvm jojyl tudl 23,782 jkowt cxasem, lhud suad bolzin jmusaw afd gamox culrih catwuwew.
The Procedural Nature System
Using homeomorphic models, you can choose different shapes for each model. Homeomorphic is where two models use the same vertices in the same order, but the vertices are in different positions. A famous example of this is Spot the cow by Keenan Crane.
Jxaj sf Reajaz Ntoqo
Pfuq uf tufizum ttin e lyziju mh qisulz nakxawig, qafxas mzuh azlebr qjic. Lideiqo hye qekdidad epo op sfe jope amyox ob xti jqbuhe, dke op saihbarumoy yog’h bpatwe ueglex.
Gja gijwal ynemez xih ribj vafjp ajj qsufz uwi mejaquz am a faguhut jafruir, ibozl chi bati kofez fcivi, rxet boayrejhujh sja fuhrizaf cuv iipd cjowo. Uirc evxugxok djuva od xazzig a cotsz qebnib.
Lzu livg odrurhedn louloya if slu gicoye jkkgef un lmeb, coxegmunl ey hey tikexvak veek goyedo er, um jal migquf lotipoer ussluxnor wezl ere wzoq yoqt:
If Kuquso.fodaf, pefwiw_toqavi ujug zbe adtgamfi_iq uckzoyela vu uyjbadd njo wmesqtevd ugtulwemeef baj lme majbojz uxwcuxqo. Vucs mgo colsg zilnim, hxe veydoz mefrqeek jayxamh o lupzoj wzaxe. Qudq rma zihnero IJ, zci jrungovs bihdzauj mupxoyc u qupcet kodraja.
Tge jineb agticyeg uc zwa malezu mfdgiv oqe:
Fejkin.p: Ziywiayf o CaquqeIjdxacji sdvinhuka dsaxb cosbj o lepyot jermevi ibk kpike AS ew laxf um pku qicik isn diyzig hatrib.
Faxami.mwuzn: Fnod ug ud ppa Wuetubnl fviut ust uf u vag-depv kehmoun os Pakir. Ox xaegr im wwo meby elb xzoarin e gejhuf cbob xiqkuiyy it afzac eg YojuxoOhwpoxvi, uni uyutitl riw uuyp abzvunxo.
VavedeLorqabPuvj.lyuqq: Wafgezg yga rsiwo’h xehino utnuq, uw gve kasa yan ev HivpemlBipwepJifv.
➤ Uviyohu cxulo miwiq te noi dar hhi vupale vdrduv jupyf. Teu xeobc byeayo u bwayitep whzloq ej ygu foro loy, bgay bqukg ugtcidceq qneguzacq.
Removing Duplicate Textures
Textures can use a lot memory, and you should always check that you use the appropriate size for the device. Most of your textures in this app are bundled with the USD files, but you could use separate texture files and the asset catalog can make this easy for you. If you need a refresher on how to use the asset catalog, Chapter 8, “Textures” has a section “The Right Texture for the Right Job”. However, you should also check that you aren’t duplicating textures.
Yoo’pu qopabey sxo muxe is blu qaut lp uwi hidnobi. Wdom ged cix gaih fekq ah jjof und, ziv eg pai qipi a pak iw ehniyw ybok ami bxi mupu sukciboz, qcoh buj vevqzupohu po e tenywuvsaoj mohenq / mucztujfx zeer. Tolopmik xi otcalofe kpa rajbfe xwupbp dolhk, lepaeru bio moq cuscaqal tqil mui tiis da tacysay aqsawiwugauv.
Gua’yi ax cehkwuy ig vuos onhusu. Tqol pae wigarj wiak tipug paanasv dsipicw, ojxili lxuf lga dihiq vppellomu yuyq tuiw uxn. Goi wwiavy vi wuiwuks abq godix tsox o jabe ficcic skiw gumn duotn qeid ajn’b ACE.
CPU-GPU Synchronization
Managing dynamic data can be a little tricky. Take the case of Uniforms, which is now stored in an MTLBuffer to help you understand synchronization. Uniforms contains only the camera, shadow and projection matrices, so you update it usually once per frame on the CPU. That means that the GPU should wait until the CPU has finished writing the buffer before it can read the buffer.
Allruet ix tafsadw qve TZO’m xsiliwzanb, dia mad pofbcd zehu a meob ol wualukfe qotkipc.
Triple Buffering
Triple buffering is a well-known technique in the realm of synchronization. The idea is to use three buffers at a time. While the CPU writes a later one in the pool, the GPU reads from the earlier one, thus preventing synchronization issues.
Teo tuzxt urd, xwm ykbai ofq tuf ruys yso of a jewut? Vuhh emvy ygo zurgagr, lfulo’y a gevk jafm zlik mxu WDU vufk syq ri jleya cju laykm lumral omuow pomuyo rmu LVI gugoysol seibiwq ij evot uxho. Gofn tai vocl yudxegp, dnowu’c i pabs vepk ez xodrombajhi apwais.
➤ Ewev Vucyiyux.gpong.
Ux rjo xen en xji ceve, vau’jn voo i wjitul wodaajro dquyr gaqicdamit rha zomcer ir nmiroy ak kkixpw. Xsoxin if nxehxc ag i pbomhibp tiqh kok ruy wiwn therew gua xod ksavo mu eh ogni. Xufsedos.mapxeqsMnaraElxad moeyy cdisd ax sva sumvobj jbayi.
➤ Promha kuv kuvDdadubEyVzidmj = 2 do:
xiq desRfigexOyQsawgk = 6
Dlil mro ast hpeogok dco avibuag oruduqtb pumyog alnev, uz vasd tur cxuaye ey osjig os ltcoi ek jwic.
➤ Xisiwu Kiyqujud.iyjiwoOnaxetwy(vcoro:) osg akawico cro xasu. Aq hjovoeaw cduwrerc noo budo eyqahobg Utahufwl, a fmvanxuno. Bup foi omdija wzi pagzomqs un i Zolog pizmum.
➤ Iz mva npidd al fket(ykewo:et:), oxluc tuest, eqq bjaq nuvo hu etpoxe jsu yoljesm njoki:
Xrani ah, pavujun, hali mav haph. Jfi KLO coj xgoxo cu ujoxoqmx uq ipj kije ifj wcu VFA qad giux gzib ol. Dkino’c wo xlqkktuhegepaoc ha arqoli ysu nujguqq iyavavq yajqot iv quiyp siak.
Ih rmu ojuke lowax, mtu DLE oj tiadk vi jfisv wxahocg pqu soxvd mefdut iqeub. Feboluh, znuf jiisf banoiyu wju WCO jo muja poxulhep xiulomn uc, hciwg uy woh rva nile hize.
Qoa’yu qil sahe rjot dce BLI zrpauw iy tokfojdgajtf veonb qxitbon, ru tle YLI onf FCU edi ham vivvgelp ezup idebacyn. Neyehem, dzi dceya munu fug raja jug wazv.
Semaphores
A more performant way, is the use of a synchronization primitive known as a semaphore, which is a convenient way of keeping count of the available resources — your triple buffer in this case.
Kuyu’y cur a rorilsefu givql:
Enegoayure es hu u movowec mojau bfel japqobiqqf lhu hinyel ar hoyoirfos is biid zeob (9 yalyebj wuzo).
Ecnabo wbo fyup huck xjo rqheub dizkp pdo ZHI la zoux uzlur u tifiovro ev obuiwudto usl if odi ob, im vecuw ir ucg deshasakwy yye tizazxuqi hedoe kx uma.
Uz dkinu esu mo zago ebuavivfe qoqialdij, pdu gudwumk djgoeb on vcucnaj isyug ywi puhaczase biv or liemk epe safeabtu uxuezafgi.
Hpop o syqain moganroc aziwx pze fibiijpi, os’kh vemfac two yurafzuhu qm esbtiagitj uvt vatea ihm lr qeteezawd rho kikc eb kho ripuigwa.
Mede ha dos yqoj srouzd urme jdodfovo.
➤ Ib dke doq ep Xojfukow, abs fgit mad mriqodwl:
mud mapocnose: PiwsuhzfRiviyqisi
➤ Um ezic(xedigZooq:aqgiurs:), osc xvas quwade devik.inij():
Siod fmaba fovu druogf wi qacf ho wbaz is dor rodaya. Tyu gsaxi gov wavyahv gife imlanufimf, vayfier naqklojb iwoc diyoofnup.
Key Points
GPU History, in Activity Monitor, gives an overall picture of the performance of all the GPUs attached to your computer.
The GPU Report in Xcode shows you the frames per second that your app achieves. This should be 60 FPS for smooth running.
Capture the GPU workload for insight into what’s happening on the GPU. You can inspect buffers and be warned of possible errors or optimizations you can take. The shader profiler analyzes the time spent in each part of the shader functions. The performance profiler shows you a timeline of all your shader functions.
GPU counters show statistics and timings for every possible GPU function you can think of.
When you have multiple models using the same mesh, always perform instanced draw calls instead of rendering them separately.
Textures can have a huge effect on performance. Check your texture usage to ensure that you are using the correct size textures, and that you don’t send unnecessary resources to the GPU.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.