Some ways to detect app performance in iOS

Source: Internet
Author: User

First, if the application is stuck or because the memory is too large, it is usually used in instruments to detect. But for complex situations it may be necessary to use the way that child threads monitor the main thread, and I'll introduce these methods: Time Profiler

You can look at ways in which the methods in multiple threads are too time consuming. Tick the right hide System libraries to filter the information. The call tree will then be sorted by default on a time-consuming thread, and a single thread will be sorted by the corresponding time-consuming method, which can be optimized by double-clicking on the heaviest Stack trace in the right-hand side to see the specific time-consuming operation code. There is no need to over-optimize in some places where performance might not have been affected.

Allocations

Here you can generations the front and back of each action, compare the increase in memory, and look at the exact method and location of the code where the memory is added. The specific action is to click Mark Generation in the right Generation analysis, which will produce a Generation, switch to another page, or a period of time to create another event. Generation to generate a new generation, so repeatedly, to generate multiple generation, view these several generation will see the size of growth, if too big can point in to see the corresponding occupied larger thread right heaviest Stack trace to view the corresponding code block, and then do the appropriate processing.

Leak

You can see the overflow in the leaks section of the area above, and after selecting the Statistics>allocation summary in the area below, you can see the leaked objects, as well as using stack trace to see the corresponding code area.

Development needs to be aware of how to avoid some performance problems nsdateformatter

Through instruments detection will find the creation of NSDateFormatter or set the properties of NSDateFormatter is always in front of the time, how to deal with this problem, it is recommended to add properties or create static variables, This allows the creation of initialization to be minimized. There is the right to use C, or the NSData category to solve https://github.com/samsoffes/sstoolkit/blob/master/SSToolkit/NSData% 2bsstoolkitadditions.m

UIImage

This is mainly to affect the memory cost, need to weigh the next imagednamed and Imagewithcontentsoffile, understand the characteristics of the two, in the only need to display a picture with the latter, which will reduce the memory consumption, but the page display will increase the consumption of image Io, This needs to be taken care of. Because Imagewithcontentsoffile does not cache, it needs to be loaded once per page display, and the operation of this IO is a point to consider the tradeoff.

Page load

If there is too much content on a page, too many views, so that the part of the view that needs to be scrolled in the long page is loaded by opening a new thread synchronization.

Optimize first load time

Time Profier can be used to see how long it takes to start up, and if it is too lengthy, it can be modified by heaviest Stack trace.

How to monitor the lag

There is also a way to monitor performance issues in the program. Can look at this demo first, address Https://github.com/ming1016/DecoupleDemo. This can be done on-line after the user's lag operation record down, timed to their own server, so that a wider range of collection performance issues. As we all know, user-level perception of the stutter is from the process of processing all the UI on the main thread, including large computations on the main thread, a large number of IO operations, or relatively heavy drawing work. How to monitor the main thread, the first thing to know is that the main thread and other threads are driven by Nsrunloop. You can take a look at Cfrunlooprun's approximate logic.

int32_t__cfrunlooprun () {__cfrunloopdoobservers (Kcfrunloopentry);do {__cfrunloopdoobservers (Kcfrunloopbeforetimers);__cfrunloopdoobservers (Kcfrunloopbeforesources);This is where processing time between kcfrunloopbeforewaiting is the key to the perception lag.__cfrunloopdoblocks ();__cfrunloopdosource0 ();Handling UI EventsGCD Dispatch Main queueCheckifexistmessagesinmaindispatchqueue ();Before hibernation__cfrunloopdoobservers (kcfrunloopbeforewaiting);Wait for MSGmach_port_t wakeupport = sleepandwaitforwakingupports (); //wait in //Hibernate, Wake __cfrunloopdoobservers ( kcfrunloopafterwaiting); //timer wake if (Wakeupport = timerport) __cfrunloopdotimers ( ); //Asynchronous processing else if (Wakeupport = maindispatchqueueport) __cfrunloop_is_servicing_the_main_dispatch_queue__ () //UI, animation else __cfrunloopdosource1 (); //ensure synchronization __cfrunloopdoblocks ();} while (!stop &&!timeout); //exit Runloop __cfrunloopdoobservers (cfrunloopexit);}      

According to this runloop we can measure by Cfrunloopobserverref. Use the dispatch_semaphore_t in the GCD to open a new thread, set a limit value and the value of the number of occurrences, Then get the scene that exceeds the limit and number of occurrences on the main thread from kcfrunloopbeforesources to kcfrunloopbeforewaiting to kcfrunloopafterwaiting two states, Dump the stack down, and finally send it to the server to do the collection, through the stack to find the corresponding problem of the method.

StaticvoidRunloopobservercallback (Cfrunloopobserverref Observer,Cfrunloopactivity activity,void *info) {MyClass *object = (__bridge myclass*) info; object->activity = activity;}StaticvoidRunloopobservercallback (Cfrunloopobserverref Observer,Cfrunloopactivity activity,void *info) {smlagmonitor *lagmonitor = (__bridge smlagmonitor*) info; lagmonitor->runloopactivity = activity;dispatch_semaphore_t semaphore = lagmonitor->dispatchsemaphore;Dispatch_semaphore_signal (semaphore);} - (void) Endmonitor {if (!runloopobserver) {Return }Cfrunloopremoveobserver (Cfrunloopgetmain (), Runloopobserver,Kcfrunloopcommonmodes);Cfrelease (Runloopobserver); Runloopobserver =NULL;} - (void) Beginmonitor {if (runloopobserver) {Return } Dispatchsemaphore =Dispatch_semaphore_create (0);Dispatch Semaphore Guarantee SynchronizationCreate an ObserverCfrunloopobservercontext context = {0, (__bridgevoid*) Self,NullNULL}; Runloopobserver =Cfrunloopobservercreate (Kcfallocatordefault,Kcfrunloopallactivities, YES,0, &runloopobservercallback, &context);Adding observers to the common mode of the main thread RunloopCfrunloopaddobserver (Cfrunloopgetmain (), Runloopobserver,Kcfrunloopcommonmodes);Creating Child thread monitoringDispatch_async (Dispatch_get_global_queue (0,0), ^{The child thread opens a continuous loop for monitoringwhile (YES) {Long semaphorewait =Dispatch_semaphore_wait (Dispatchsemaphore,Dispatch_time (Dispatch_time_now,30*nsec_per_msec)); if (semaphorewait! = 0) {if (!runloopobserver) { Timeoutcount = 0; dispatchsemaphore = 0; runloopactivity = 0; return;} //two runloop states, Beforesources and afterwaiting These two state interval time can detect whether the lag if ( Runloopactivity = = kcfrunloopbeforesources | | runloopactivity =  kcfrunloopafterwaiting) {//appears three times results if (++timeoutcount < 3) {continue;} //put the stack information escalation server code here} //end Activity} //end semaphore Wait timeoutcount = 0;} //End While});             

Sometimes it is because of abnormal data, too much, or too large, or the abnormal appearance of the operation, such a situation may be difficult to meet in the usual daily development test, but in the real, especially the user audience is wide, people will appear, so this collection of the way is still valuable.

Method of Stack Dump

The first is to call the system function directly to get the stack information, this method can only get the simple information, unable to cooperate with dSYM to obtain the specific line of code out of the problem, the type is limited. The main idea of this method is to get the wrong signal signal. The code is as follows

Staticint s_fatal_signals[] = {SIGABRT, Sigbus, SIGFPE, Sigill, SIGSEGV, SIGTRAP, SIGTERM, SIGKILL,};Staticint s_fatal_signal_num =sizeof (s_fatal_signals)/sizeof (s_fatal_signals[0]);voidUncaughtexceptionhandler (NSException *exception) {Nsarray *exceptionarray = [exceptionCallstacksymbols];Get the current call stack informationNSString *exceptionreason = [exceptionReason];Is very important, is the cause of the collapseNSString *exceptionname = [exceptionName];Exception type}voidSignalhandler (int code) {NSLog (@ "signal handler = %d", code);} void initcrashreport () {//system error signal capture  for (int i = 0; i < s_fatal_signal_num; ++i) {signal (s_ Fatal_signals[i], Signalhandler); } //oc uncaught exception capture nssetuncaughtexceptionhandler (& Uncaughtexceptionhandler);} int main (int argc, char * argv[]) {@ Autoreleasepool {initcrashreport (); return uiapplicationmain (argc, argv, nil, nsstringfromclass ([appdelegate class]);}}       

Reports that use plcrashreporter appear to be able to pinpoint the location of the problem code.

NSData *lagdata = [[[PlcrashreporterAllocinitwithconfiguration:[[plcrashreporterconfig alloc] initwithsignalhandlertype:plcrashreportersignalhandlertypebsd  Symbolicationstrategy:plcrashreportersymbolicationstrategyall]] generateLiveReport]; Plcrashreport *lagreport = [[Plcrashreport alloc] initwithdata:lagdata error:null]; nsstring *lagreportstring = [plcrashreporttextformatter  Stringvalueforcrashreport:lagreport withtextformat:plcrashreporttextformatios]; //string upload server nslog (@ "lag happen, Detail below: %@      

Below is the contents of the stack in the test demo

2016-03-28 14:59:26.922 homepagetest[4803:201212] info:reveal Server started (Protocol Version 25). 2016-03-28 14:59:27. 134 homepagetest[4803:201212] Time-consuming test 2016-03-28 14:59:29.262 homepagetest[4803:201212] Time-consuming test 2016-03-28 14:59:30.865 HOMEPAGETEST[4803:201212] Time-consuming test 2016-03-28 14:59:32.115 homepagetest[4803:201212] Time-consuming test 2016-03-28 14:59:33.369 HOMEPAGETEST[4803:201212] Time-consuming test 2016-03-28 14:59:34.832 homepagetest[4803:201212] Time-consuming test 2016-03-28 14:59:34.836 HOMEPAGETEST[4803:201615] lag happen, detail below:incident Identifier: 73bef9d2-ebe3-49df-b95b-7392635631a3crashreporter Key:todohardware Model:x86_64Process:HomePageTest [480 3]path:/users/daiming/library/developer/coresimulator/devices/444aab95-c393-45cc-b5dc-0fb8611068f9/data/contai      Ners/bundle/application/9cee3a3a-9469-44f5-8112-ff0550ed8009/homepagetest.app/homepagetestidentifier:       com.xiaojukeji.homepagetestversion:1.0 (1) Code type:x86-64parent process:debugserver [4805]date/time:2016-03-28 06:59:34 +0000os version:mac OS X 9.2 (15D21) Report version:104exception type:sigtrapexception Codes: Trap_trace at 0x10aee6f79crashed thread:2thread 0:0 libsystem_kernel.dylib 0x000000010ec6b206 __semwait_ Signal + 101 Libsystem_c.dylib 0x000000010e9f2b9e usleep + 542 Homepagetest 0 x000000010aedf934-[testtableview Configcell] + 8203 homepagetest 0x000000010aee5c89-[testTableV Iewcontroller ObserveValueForKeyPath:ofObject:change:context:] + 6014 Foundation 0x000000010b9c   2564 Nskeyvaluenotifyobserver + 3475 Foundation 0x000000010b9c178f Nskeyvaluedidchange + 4666 Foundation 0x000000010b9bf003-[nsobject (nskeyvalueobservingprivate) _changevalueforkey:key:key: Usingblock:] + 11767 Foundation 0x000000010ba1d35f _nssetobjectvalueandnotify + 2618 homepage                    Test    0x000000010aec9c26-[dctableview Tableview:cellforrowatindexpath:] + 2629 UIKit 0x0000                               00010c872e43-[uitableview _createpreparedcellforglobalrow:withindexpath:willdisplay:] + 76610 UIKit                               0x000000010c872f7b-[uitableview _createpreparedcellforglobalrow:willdisplay:] + 7411 UIKit                               0x000000010c847a39-[uitableview _updatevisiblecellsnow:isrecursive:] + 299612 UIKit 0x000000010c87c01c-[uitableview _performwithcachedtraitcollection:] + 9213 UIKit 0x00 0000010c862edc-[uitableview Layoutsubviews] + 22414 UIKit 0x000000010c7d04a3-[uiview (CALa yerdelegate) Layoutsublayersoflayer:] + 70315 quartzcore 0x000000010c49a59a-[calayer LayoutSubl  Ayers] + 14616 Quartzcore 0x000000010c48ee70 _zn2ca5layer16layout_if_neededepns_11transactione +      36617 Quartzcore                    0x000000010c48ecee _zn2ca5layer28layout_and_display_if_neededepns_11transactione + 2418 QuartzCore                          0x000000010c483475 _zn2ca7context18commit_transactionepns_11transactione + 27719 QuartzCore 0x000000010c4b0c0a _zn2ca11transaction6commitev + 48620 Quartzcore 0x00000001 0c4bf9f4 _zn2ca7display11displaylink14dispatch_itemseyyy + 57621 Corefoundation 0x000000010e123c84 _ _cfrunloop_is_calling_out_to_a_timer_callback_function__ + 2022 Corefoundation 0x000000010e123831 __                      Cfrunloopdotimer + 108923 corefoundation 0x000000010e0e5241 __cfrunlooprun + 193724 corefoundation 0x000000010e0e4828 cfrunlooprunspecific + 48825 graphicsservices 0x0000000110479a                         D2 Gseventrunmodal + 16126 UIKit 0x000000010c719610 uiapplicationmain + 17127 homepagetest0X000000010AEE0FDF main + 11128 libdyld.dylib 0x000000010e92b92d start + 1Thread 1:0 Libsystem_ke Rnel.dylib 0x000000010ec6bfde Kevent64 + 101 Libdispatch.dylib 0x000000010e8e6262 _dispat   Ch_mgr_init + 0Thread 2 crashed:0 Homepagetest 0x000000010b04a445-[plcrashreporter generatelivereportwiththread:error:] + 6321 Hom Epagetest 0x000000010aee6f79 __28-[smlagmonitor Beginmonitor]_block_invoke + 4252 Libdispatch.dyl IB 0x000000010e8d6e5d _dispatch_call_block_and_release + 123 Libdispatch.dylib 0x000 000010e8f749b _dispatch_client_callout + libdispatch.dylib 0x000000010e8dfbef _dispatch_root_queue_ Drain + 18295 Libdispatch.dylib 0x000000010e8df4c5 _dispatch_worker_thread3 + 1116 Libsystem_pthread . dylib 0x000000010ec2f68f _pthread_wqthread + 11297 libsystem_pthread.dylib 0x000000010ec2d365 Start_wqthread + 13Thread 3:0 libsystem_kernel.dylib 0x000000010ec6b6de __workq_kernreturn + 101              Libsystem_pthread.dylib 0x000000010ec2d365 start_wqthread + 13Thread 4:0 libsystem_kernel.dylib 0x000000010ec65386 Mach_msg_trap + 101 corefoundation 0x000000010e0e5b64 __cfrunloopservicemach                      Port + 2122 corefoundation 0x000000010e0e4fbf __cfrunlooprun + 12953 corefoundation 0x000000010e0e4828 cfrunlooprunspecific + 4884 WebCore 0x0000000113408f65 _zl12runwe             BTHREADPV + 4695 libsystem_pthread.dylib 0x000000010ec2fc13 _pthread_body + 1316 Libsystem_pthread.dylib 0x000000010ec2fb90 _pthread_body + libsystem_pthread.dylib 0x000000010ec2d375 Thread_start + 1             3Thread 5:0 libsystem_kernel.dylib 0x000000010ec6b6de __workq_kernreturn + 101 Libsystem_pthread.dylib 0x000000010ec2d365 Start_wqthread + 13Thread 6:0 libsystem_kernel.dylib 0x000000010ec6b6de __workq_kernreturn + 101 Lib System_pthread.dylib 0x000000010ec2d365 start_wqthread + 13Thread 7:0 libsystem_kernel.dylib 0x 000000010ec6b6de __workq_kernreturn + 101 libsystem_pthread.dylib 0x000000010ec2d365 Start_wqthread + 13Thre    Ad 2 crashed with x86-64 Thread state:rip:0x000000010b04a445 rbp:0x0000700000093da0 RSP:0X0000700000093B10 Rax:0x0000700000093b70 rbx:0x0000700000093cb0 rcx:0x0000000000001003 rdx:0x0000000000000000 rdi:0x0000000 10B04A5CA RSI:0X0000700000093B40 r8:0x0000000000000014 r9:0x0000000000000000 r10:0x000000010ec65362 R 11:0x0000000000000246 r12:0x00007fdaf5800940 r13:0x0000000000000000 r14:0x0000000000000009 r15:0x00007000  00093b90 rflags:0x0000000000000202 cs:0x000000000000002b fs:0x0000000000000000 gs:0x0000000000000000

 

Some ways to detect app performance in iOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.