SlideShare a Scribd company logo
1 of 34
Download to read offline
1
Марина Звягина


Vivid Money
Используем MetricKit


в бою
План
3
1 MetricKit - основные сущности и как с ними работать


2 Примеры и истории из нашей практики


3 Итоги
4
MXMetricManager
MXMetricManagerSubscriber
MXMetricPayload
MXDiagnosticPayload
MXAppLaunchMetric
MXAppResponsivenessMetric
MXDiskIOMetric
MXMemoryMetric
MXDisplayMetric
MXAnimationMetric
MXAppExitMetric
MXSignpostMetric
MXMetaData
MXCPUExceptionDiagnostic
MXDiskWriteExceptionDiagnostic
MXHangDiagnostic
MXCrashDiagnostic
MetricKit
MXHistogram
MXMetric
5
MXMetricManager
let metrikManager = MXMetricManager.shared


metrikManager.add(self)
open func add(_ subscriber: MXMetricManagerSubscriber)
open func remove(_ subscriber: MXMetricManagerSubscriber)
@available(iOS 13.0, *)
open var pastPayloads: [MXMetricPayload] { get }
open var pastDiagnosticPayloads: [MXDiagnosticPayload] { get }
@available(iOS 14.0, *)
What’s New in MetricKit
6
MXMetricManagerSubscriber
optional func didReceive(_ payloads: [MXMetricPayload])
optional func didReceive(_ payloads: [MXDiagnosticPayload])
MXMetricPayload
includesMultipleApplicationVersions Bool


latestApplicationVersion NSTaggedPointerString "1.77.0"


metaData MXMetaData


regionFormat NSTaggedPointerString @"RU"


osVersion NSCFString @"iPhone OS 15.2 (19C56)"


deviceType NSCFString @"iPhone 13,4"


applicationBuildVersion NSTaggedPointerString @"1"


platformArchitecture NSTaggedPointerString @"arm64e"


timeStampBegin NSTaggedDate 2022-02-03 21:00:00 UTC


timeStampEnd NSTaggedDate 2022-02-04 21:00:00 UTC
🤩
MXMetricPayload
applicationResponsivenessMetrics MXAppResponsivenessMetric


histogrammedAppHangTime (buckets)


diskIOMetrics MXDiskIOMetric


cumulativeLogicalWrites "1300kB"


locationActivityMetrics MXLocationActivityMetric


cumulativeBestAccuracyTime "20 sec"


cumulativeBastAccuracyForNavigationTime


cumulativeNearestTenMetersAccuracyTime


cumulativeHundredMetersAccuracyTime


cumulativeKilometerAccuracyTime


cumulativeThreeKilometersAccuracyTime
🤩
Improving Your App's Performance
AnyHashable("applicationResponsivenessMetrics"): {


histogrammedAppHangTime = {


histogramNumBuckets = 3;


histogramValue = {


0 = {


bucketCount = 50;


bucketEnd = "100 ms";


bucketStart = "0 ms";


};


1 = {


bucketCount = 60;


bucketEnd = "400 ms";


bucketStart = "100 ms";


};


2 = {


bucketCount = 30;


bucketEnd = "700 ms";


bucketStart = "400 ms";


};


};


};


}
9
MXMetricPayload 🤩
applicationLaunchMetrics MXAppLaunchMetric


histogrammedTimeToFirstDraw


histogrammedApplicationResumeTime


histogrammedOptimizedTimeToFirstDraw
What’s New in MetricKit
10
@available(iOS 14.0, *)
Нормальный выход
Вытеснено другим приложением в foreground
Переходы между стейтами занимают больше 20 секунд
MXMetricPayload 🤩
cumulativeBadAccessExitCount


cumulativeIllegalInstructionExitCount


cumulativeAbnormalExitCount


cumulativeCPUResourceLimitExitCount


cumulativeMemoryResourceLimitExitCount


cumulativePressureExitCount


cumulativeSuspendedWithLockedFileExitCount


cumulativeAppWatchdogExitCount


cumulativeBackgroundTaskAssertionTimeoutExitCount


cumulativeNormalExitCount


Crashes


Segmentation fault


Illegal instruction


Asserts and uncaught exceptions
Understanding Crashes and Crash Logs
Why is my app getting killed
MXBackgroundExitData
Рассмотрим вместе с MXDiagnosticPayload
11
MXMetricPayload 🤔
cellularConditionMetrics MXCellularConditionMetric
cellConditionTime = {
histogramNumBuckets = 3;
histogramValue = {
0 = {
bucketCount = 20;
bucketEnd = "1 bars";
bucketStart = "1 bars";
};
1 = {
bucketCount = 30;
bucketEnd = "2 bars";
bucketStart = "2 bars";
};
2 = {
bucketCount = 50;
bucketEnd = "3 bars";
bucketStart = "3 bars";
};
};
};
Custom Metric
12
let logHandle = MXMetricManager.makeLogHandle(category: "HomeScreen")


mxSignpost(.begin, log: logHandle, name: "homeScreenLaunching")


mxSignpost(.end, log: logHandle, name: "homeScreenLaunching")
MXSignpostMetric
histogram count
mxSignpost(.event, log: logHandle, name: "homeScreenLaunching")
os_signpost
13
mxSignpost vs os_signpost
1.29ms vs 1.17ms
14
MXDiagnosticPayload
cpuExceptionDiagnostics: [MXCPUExceptionDiagnostic]? cpuMetrics
diskWriteExceptionDiagnostics: [MXDickWriteExceptionDiagnostic]? diskIOMetrics
hangDiagnostics: [MXHangDiagnostic]? applicationResponsivenessMetrics
crashDiagnostics: [MXCrashDiagnostic]? applicationExitMetrics
15
MXCPUExceptionDiagnostic
CPU Exception, or a "high CPU usage termination"
80% CPU over a period of one minute (on background execution)
Why is my app getting killed
Solving CPU Usage Crashes with Xcode's Energy Organizer
cumulativeCPUResourceLimitExitCount
Чтобы избежать этого exception'а:


move work into BGProcessingTask
MXBackgroundExitData
16
MXDiskWriteExceptionDiagnostic
"diskIOMetrics": {
cumulativeLogicalWrites = "1300 kB"
}
Генерируется, если количество записей > 1 ГБ в день
"callStackTree" : {
"callStacks" : [
{
"callStackRootFrames" : [
{
…
"sampleCount" : 20
"diagnosticMetaData" : {
…
"regionFormat" : "GB",
"writesCaused" : "2,000 byte"
…
}
A disk write exception occurs when the app writes an excessive amount of data to the disk.
diskIOMetrics MXDiskIOMetric


cumulativeLogicalWrites "1300kB"
17
MXCrashDiagnostic
MXBackgroundExitData
cumulativeBadAccessExitCount


cumulativeIllegalInstructionExitCount


cumulativeAbnormalExitCount
MXCrashDiagnostic


• Stack trace


• Signal


• Exception code


• Termination reason
18
MXHangDiagnostic
Eliminate animation hitches with XCTest
Все данные unsymbolicated - можно использовать утилиту ATOS
cd ~/Library/Developer/Xcode/Archives/2022-01-26/Vivid 26.01.2022, 20.43.xcarchive/dSYMs/Vivid.app.dSYM/Contents/Resources/DWARF/

atos -arch arm64 -o myApp 0x4329526096
Identify trends with the Power and Performance API
An object representing a diagnostic report for an app that is too busy


to handle user input responsively
applicationResponsivenessMetrics MXAppResponsivenessMetric


histogrammedAppHangTime (buckets)
19
MXMetricPayload Test payloads
План
20
1 MetricKit - основные сущности и как с ними работать


2 Примеры и истории из нашей практики


3 Итоги
✅
21
reality
+ +
In
fl
ux data input format
Telegraf
VictoriaMetrics
Grafana
vivid
22
reality.code
23
struct PerformanceMeasure {


var callTime: TimeInterval


let type: PerformanceMeasureType


let concreteName: String?


var stopTime: TimeInterval?


}
struct TelegrafEvent {


let name: String


let time: TimeInterval


let tags: [String: String]


let metricType: TelegrafMetricType


}
let time = measure.stopTime - measure.callTime
Date().timeIntervalSince1970
vivid
24
App launch metric
func measureAppStartUpTime() -> (Double, Double) {


var kinfo = kinfo_proc()


var size = MemoryLayout<kinfo_proc>.stride


var mib : [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]


sysctl(&mib, u_int(mib.count), &kinfo, &size, nil, 0)


let startTime = kinfo.kp_proc.p_starttime


var time = timeval(tv_sec: 0, tv_usec: 0)


gettimeofday(&time, nil)


let currentTimeMilliseconds = (Double(Int64(time.tv_sec) * 1_000) + Double(time.tv_usec) / 1_000.0) / 1_000.0


let processTimeMilliseconds = (Double(Int64(startTime.tv_sec) * 1_000) + Double(startTime.tv_usec) / 1_000.0) /
1_000.0


return (processTimeMilliseconds, currentTimeMilliseconds)


}
vivid
25
26
MetricKit
@available(iOS 13.0, *)


func didReceive(_ payloads: [MXMetricPayload]) {


payloads.forEach { payload in


print(payload.dictionaryRepresentation())




var currentSaveValues: [String] = payloadsStored.get() ?? []


currentSaveValues.append("MXMetricPayload = (payload.dictionaryRepresentation().description)")


payloadsStored.set(value: currentSaveValues)




let firstDrawBuckets: [MXHistogramBucket] =


(payload.applicationLaunchMetrics?.histogrammedTimeToFirstDraw.bucketEnumerator.allObjects as?
[MXHistogramBucket<Unit>])


.rescue([])




firstDrawBuckets.forEach { bucket in


addMetricsIfNeeded(bucket: bucket, measureType: .appLaunchMetricsTime)


}




let resumeBackets: [MXHistogramBucket] =


(payload.applicationLaunchMetrics?.histogrammedApplicationResumeTime.bucketEnumerator.allObjects


as? [MXHistogramBucket<Unit>])


.rescue([])




resumeBackets.forEach { bucket in


addMetricsIfNeeded(bucket: bucket, measureType: .appResumeMetricsTime)


}


}


}
vivid
27
28
struct PerformanceNewMeasure {


var callTime: TimeInterval


let type: PerformanceMeasureType


let concreteName: String?


var stopTime: TimeInterval?


}
struct TelegrafEvent {


let name: String


let time: TimeInterval


let tags: [String: String]


let metricType: TelegrafMetricType


}
let time = measure.stopTime - measure.callTime
Date().timeIntervalSince1970
Date().timeIntervalSince1970
event.time.multiply(1_000)
Ответ
Date().timeIntervalSince1970
vivid reality.code
29
histogrammedTimeToFirstDrawKey = {
histogramNumBuckets = 3;
histogramValue = {
0 = {
bucketCount = 50;
bucketEnd = "1010 ms";
bucketStart = "1000 ms";
};
1 = {
bucketCount = 60;
bucketEnd = "2010 ms";
bucketStart = "2000 ms";
};
2 = {
bucketCount = 30;
bucketEnd = "3010 ms";
bucketStart = "3000 ms";
};
};
};
"time_obtain_short_i,name=BeforeApp,env=stable,ver=1.77.0 ms=682.904005050659"
vivid reality.code
30
@available(iOS 13.0, *)


func addMetricsIfNeeded(bucket: MXHistogramBucket<Unit>, measureType: PerformanceMeasureType) {


let bucketEnd = bucket.bucketEnd


let bucketStart = bucket.bucketStart


let countOfEvents = bucket.bucketCount




if bucketEnd.unit.symbol == "ms" && bucketStart.unit.symbol == "ms" {


let averageValue = (bucketEnd.value.plus(bucketStart.value)) / 2


let appLaunchEvent = performanceTracker.getEvent(with: .fastRequestLoading)




guard countOfEvents > 0 else { return }




for _ in 1...countOfEvents {


appLaunchEvent.addMeasure(callTime: 0, stopTime: averageValue, measureType:
measureType, kind: .simple)


}


}


}
vivid reality.code
reality Grafana
31
vivid
План
32
1 MetricKit - основные сущности и как с ними работать


2 Примеры и истории из нашей практики


3 Итоги
✅
✅
33
💚 MetricKit легко добавить
💚 MetricKit можно использовать вместе с остальными метриками, но есть 2 нюанса:
- Нужно учитывать, в каком они формате (их 3 - бакеты, количество и длительность)

- Следить за единицами измерения

💚 Удобно использовать метрики в связке с Pro
fi
ler и с Organizer - они позволяют смотреть в моменте
и регресс, а MetricKit позволяет смотреть в динамике от сборки к сборке

💚 Сопоставление MXMetricPayload vs MXDiagnosticPayload

❌ MXDiagnostic не доступен без dSYMs - не получится в реальном времени отслеживать данные

❌ Не все метрики кажутся полезными
❌ Perf tests
Итоги
MetricKit
What’s New in MetricKit
Improving Your App's Performance
Understanding Crashes and Crash Logs
Why is my app getting killed
Solving CPU Usage Crashes with Xcode's Energy Organizer
Eliminate animation hitches with XCTest
Identify trends with the Power and Performance API
Telegraf
VictoriaMetrics
Grafana
https://stackoverflow.com/questions/64378095/metrickit-mxdiagnostic-symbolication


https://swiftrocks.com/debug-cpu-exceptions-xcode-energy-reports


https://medium.com/naukri-engineering/overview-of-dsym-crashlytics-in-ios-dfd72eae8b58
iOS Performance Engineer Android Performance Engineer
https://jobs.vivid.money/jobs/Careers/33579000004386184/iOS-developer-Performance-team-?source=CareerSite


https://jobs.vivid.money/jobs/Careers/33579000004386170/Android-developer-Performance-team-?source=CareerSite

More Related Content

What's hot

ALAT PEDETEKSI ORANG MEROKOK DALAM TOILET MENGGUNAKAN SENSOR ASAP BERBASIS AR...
ALAT PEDETEKSI ORANG MEROKOK DALAM TOILET MENGGUNAKAN SENSOR ASAP BERBASIS AR...ALAT PEDETEKSI ORANG MEROKOK DALAM TOILET MENGGUNAKAN SENSOR ASAP BERBASIS AR...
ALAT PEDETEKSI ORANG MEROKOK DALAM TOILET MENGGUNAKAN SENSOR ASAP BERBASIS AR...Joni Candra
 
Speaker Event with Dr. Susan C. Pannullo - Brain Tumor Foundation
Speaker Event with Dr. Susan C. Pannullo - Brain Tumor FoundationSpeaker Event with Dr. Susan C. Pannullo - Brain Tumor Foundation
Speaker Event with Dr. Susan C. Pannullo - Brain Tumor FoundationBrain Tumor Foundation
 
Matlab Untuk Pengolahan Citra
Matlab Untuk Pengolahan CitraMatlab Untuk Pengolahan Citra
Matlab Untuk Pengolahan Citraarifgator
 
Apollo hydbd feb8 2013 (cancer ci 2013) p. mahadev md
Apollo hydbd feb8 2013 (cancer ci 2013) p. mahadev mdApollo hydbd feb8 2013 (cancer ci 2013) p. mahadev md
Apollo hydbd feb8 2013 (cancer ci 2013) p. mahadev mdDr. Vijay Anand P. Reddy
 
Wstęp do Planowania Leczenia w Teleradioterapii
Wstęp do Planowania Leczenia w TeleradioterapiiWstęp do Planowania Leczenia w Teleradioterapii
Wstęp do Planowania Leczenia w TeleradioterapiiTomasz Piotrowski
 
01 suh brain anatomy, planning and delivery hyderabad 2013 (cancer ci 2013) j...
01 suh brain anatomy, planning and delivery hyderabad 2013 (cancer ci 2013) j...01 suh brain anatomy, planning and delivery hyderabad 2013 (cancer ci 2013) j...
01 suh brain anatomy, planning and delivery hyderabad 2013 (cancer ci 2013) j...Dr. Vijay Anand P. Reddy
 
Iv curah hujan, analisis data hilang, peluang hujan dan evapotranspirasi gtr
Iv curah hujan, analisis data hilang, peluang hujan dan evapotranspirasi gtrIv curah hujan, analisis data hilang, peluang hujan dan evapotranspirasi gtr
Iv curah hujan, analisis data hilang, peluang hujan dan evapotranspirasi gtrGusti Rusmayadi
 
Dose Constraints In Imrt
Dose Constraints In ImrtDose Constraints In Imrt
Dose Constraints In Imrtfondas vakalis
 
Vmat technique for Breast, Head and Neck, Brain and Craniospinal irradiation ...
Vmat technique for Breast, Head and Neck, Brain and Craniospinal irradiation ...Vmat technique for Breast, Head and Neck, Brain and Craniospinal irradiation ...
Vmat technique for Breast, Head and Neck, Brain and Craniospinal irradiation ...Biplab Sarkar
 
Penjelasan tentang kontur dan representasi citra
Penjelasan tentang kontur dan representasi citraPenjelasan tentang kontur dan representasi citra
Penjelasan tentang kontur dan representasi citraIztHo'ell Shoerento
 
Pengolahan Citra Digital Dengan Menggunakan MATLAB
Pengolahan Citra Digital Dengan Menggunakan MATLABPengolahan Citra Digital Dengan Menggunakan MATLAB
Pengolahan Citra Digital Dengan Menggunakan MATLABSimesterious TheMaster
 
Stereotactic Radio-Surgery/Therapy (SRS/SRT)
 Stereotactic Radio-Surgery/Therapy (SRS/SRT) Stereotactic Radio-Surgery/Therapy (SRS/SRT)
Stereotactic Radio-Surgery/Therapy (SRS/SRT)Aaditya Sinha
 
Systems of Brachy.ppt
Systems of Brachy.pptSystems of Brachy.ppt
Systems of Brachy.pptSheedh4
 
FSMA(食品安全近代化法)より準備しておかないといけないこと
FSMA(食品安全近代化法)より準備しておかないといけないことFSMA(食品安全近代化法)より準備しておかないといけないこと
FSMA(食品安全近代化法)より準備しておかないといけないことYUMIKO HIRAI
 
implementasi-dan-maintenance
implementasi-dan-maintenanceimplementasi-dan-maintenance
implementasi-dan-maintenanceIwan Kurniarasa
 

What's hot (20)

9.algoritma kriptografi klasik (bag 5)xx
9.algoritma kriptografi klasik (bag 5)xx9.algoritma kriptografi klasik (bag 5)xx
9.algoritma kriptografi klasik (bag 5)xx
 
Kelompok 6 prototipe
Kelompok 6   prototipeKelompok 6   prototipe
Kelompok 6 prototipe
 
ALAT PEDETEKSI ORANG MEROKOK DALAM TOILET MENGGUNAKAN SENSOR ASAP BERBASIS AR...
ALAT PEDETEKSI ORANG MEROKOK DALAM TOILET MENGGUNAKAN SENSOR ASAP BERBASIS AR...ALAT PEDETEKSI ORANG MEROKOK DALAM TOILET MENGGUNAKAN SENSOR ASAP BERBASIS AR...
ALAT PEDETEKSI ORANG MEROKOK DALAM TOILET MENGGUNAKAN SENSOR ASAP BERBASIS AR...
 
Speaker Event with Dr. Susan C. Pannullo - Brain Tumor Foundation
Speaker Event with Dr. Susan C. Pannullo - Brain Tumor FoundationSpeaker Event with Dr. Susan C. Pannullo - Brain Tumor Foundation
Speaker Event with Dr. Susan C. Pannullo - Brain Tumor Foundation
 
Matlab Untuk Pengolahan Citra
Matlab Untuk Pengolahan CitraMatlab Untuk Pengolahan Citra
Matlab Untuk Pengolahan Citra
 
Apollo hydbd feb8 2013 (cancer ci 2013) p. mahadev md
Apollo hydbd feb8 2013 (cancer ci 2013) p. mahadev mdApollo hydbd feb8 2013 (cancer ci 2013) p. mahadev md
Apollo hydbd feb8 2013 (cancer ci 2013) p. mahadev md
 
Wstęp do Planowania Leczenia w Teleradioterapii
Wstęp do Planowania Leczenia w TeleradioterapiiWstęp do Planowania Leczenia w Teleradioterapii
Wstęp do Planowania Leczenia w Teleradioterapii
 
01 suh brain anatomy, planning and delivery hyderabad 2013 (cancer ci 2013) j...
01 suh brain anatomy, planning and delivery hyderabad 2013 (cancer ci 2013) j...01 suh brain anatomy, planning and delivery hyderabad 2013 (cancer ci 2013) j...
01 suh brain anatomy, planning and delivery hyderabad 2013 (cancer ci 2013) j...
 
Iv curah hujan, analisis data hilang, peluang hujan dan evapotranspirasi gtr
Iv curah hujan, analisis data hilang, peluang hujan dan evapotranspirasi gtrIv curah hujan, analisis data hilang, peluang hujan dan evapotranspirasi gtr
Iv curah hujan, analisis data hilang, peluang hujan dan evapotranspirasi gtr
 
Dose Constraints In Imrt
Dose Constraints In ImrtDose Constraints In Imrt
Dose Constraints In Imrt
 
Vmat technique for Breast, Head and Neck, Brain and Craniospinal irradiation ...
Vmat technique for Breast, Head and Neck, Brain and Craniospinal irradiation ...Vmat technique for Breast, Head and Neck, Brain and Craniospinal irradiation ...
Vmat technique for Breast, Head and Neck, Brain and Craniospinal irradiation ...
 
Penjelasan tentang kontur dan representasi citra
Penjelasan tentang kontur dan representasi citraPenjelasan tentang kontur dan representasi citra
Penjelasan tentang kontur dan representasi citra
 
Ricestar 69 EC-Indo
Ricestar 69 EC-IndoRicestar 69 EC-Indo
Ricestar 69 EC-Indo
 
Pengolahan Citra Digital Dengan Menggunakan MATLAB
Pengolahan Citra Digital Dengan Menggunakan MATLABPengolahan Citra Digital Dengan Menggunakan MATLAB
Pengolahan Citra Digital Dengan Menggunakan MATLAB
 
Stereotactic Radio-Surgery/Therapy (SRS/SRT)
 Stereotactic Radio-Surgery/Therapy (SRS/SRT) Stereotactic Radio-Surgery/Therapy (SRS/SRT)
Stereotactic Radio-Surgery/Therapy (SRS/SRT)
 
Systems of Brachy.ppt
Systems of Brachy.pptSystems of Brachy.ppt
Systems of Brachy.ppt
 
TEORI BAB 11
TEORI BAB 11TEORI BAB 11
TEORI BAB 11
 
FSMA(食品安全近代化法)より準備しておかないといけないこと
FSMA(食品安全近代化法)より準備しておかないといけないことFSMA(食品安全近代化法)より準備しておかないといけないこと
FSMA(食品安全近代化法)より準備しておかないといけないこと
 
implementasi-dan-maintenance
implementasi-dan-maintenanceimplementasi-dan-maintenance
implementasi-dan-maintenance
 
Layanan telematika
Layanan telematikaLayanan telematika
Layanan telematika
 

Similar to "Используем MetricKit в бою" / Марина Звягина (Vivid Money)

Observability and its application
Observability and its applicationObservability and its application
Observability and its applicationThao Huynh Quang
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010RonnBlack
 
Resillient microservices
Resillient microservicesResillient microservices
Resillient microservicesNilesh Gule
 
Spring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & MicrometerSpring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & MicrometerToshiaki Maki
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On RandomnessRanel Padon
 
Implementasi Pemodelan Sistem Ke TeeChart
Implementasi Pemodelan Sistem Ke TeeChartImplementasi Pemodelan Sistem Ke TeeChart
Implementasi Pemodelan Sistem Ke TeeChartLusiana Diyan
 
Introduction to Reactive Extensions (Rx)
Introduction to Reactive Extensions (Rx)Introduction to Reactive Extensions (Rx)
Introduction to Reactive Extensions (Rx)Tamir Dresher
 
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome Massimiliano Dessì
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트기룡 남
 
IJCER (www.ijceronline.com) International Journal of computational Engineeri...
 IJCER (www.ijceronline.com) International Journal of computational Engineeri... IJCER (www.ijceronline.com) International Journal of computational Engineeri...
IJCER (www.ijceronline.com) International Journal of computational Engineeri...ijceronline
 
Safe Clearing of Private Data
Safe Clearing of Private DataSafe Clearing of Private Data
Safe Clearing of Private DataPVS-Studio
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer developmentAndrey Karpov
 
How to monitor your micro-service with Prometheus?
How to monitor your micro-service with Prometheus?How to monitor your micro-service with Prometheus?
How to monitor your micro-service with Prometheus?Wojciech Barczyński
 
Succumbing to the Python in Financial Markets
Succumbing to the Python in Financial MarketsSuccumbing to the Python in Financial Markets
Succumbing to the Python in Financial Marketsdcerezo
 
Building responsive applications with Rx - CodeMash2017 - Tamir Dresher
Building responsive applications with Rx  - CodeMash2017 - Tamir DresherBuilding responsive applications with Rx  - CodeMash2017 - Tamir Dresher
Building responsive applications with Rx - CodeMash2017 - Tamir DresherTamir Dresher
 
Free rtos workshop3@nuu
Free rtos workshop3@nuuFree rtos workshop3@nuu
Free rtos workshop3@nuu紀榮 陳
 
Static analysis of C++ source code
Static analysis of C++ source codeStatic analysis of C++ source code
Static analysis of C++ source codePVS-Studio
 

Similar to "Используем MetricKit в бою" / Марина Звягина (Vivid Money) (20)

Observability and its application
Observability and its applicationObservability and its application
Observability and its application
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010
 
Resillient microservices
Resillient microservicesResillient microservices
Resillient microservices
 
Spring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & MicrometerSpring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & Micrometer
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On Randomness
 
Implementasi Pemodelan Sistem Ke TeeChart
Implementasi Pemodelan Sistem Ke TeeChartImplementasi Pemodelan Sistem Ke TeeChart
Implementasi Pemodelan Sistem Ke TeeChart
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Enhancing the region model of RTSJ
Enhancing the region model of RTSJEnhancing the region model of RTSJ
Enhancing the region model of RTSJ
 
Introduction to Reactive Extensions (Rx)
Introduction to Reactive Extensions (Rx)Introduction to Reactive Extensions (Rx)
Introduction to Reactive Extensions (Rx)
 
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
IJCER (www.ijceronline.com) International Journal of computational Engineeri...
 IJCER (www.ijceronline.com) International Journal of computational Engineeri... IJCER (www.ijceronline.com) International Journal of computational Engineeri...
IJCER (www.ijceronline.com) International Journal of computational Engineeri...
 
Safe Clearing of Private Data
Safe Clearing of Private DataSafe Clearing of Private Data
Safe Clearing of Private Data
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer development
 
How to monitor your micro-service with Prometheus?
How to monitor your micro-service with Prometheus?How to monitor your micro-service with Prometheus?
How to monitor your micro-service with Prometheus?
 
Succumbing to the Python in Financial Markets
Succumbing to the Python in Financial MarketsSuccumbing to the Python in Financial Markets
Succumbing to the Python in Financial Markets
 
Building responsive applications with Rx - CodeMash2017 - Tamir Dresher
Building responsive applications with Rx  - CodeMash2017 - Tamir DresherBuilding responsive applications with Rx  - CodeMash2017 - Tamir Dresher
Building responsive applications with Rx - CodeMash2017 - Tamir Dresher
 
Free rtos workshop3@nuu
Free rtos workshop3@nuuFree rtos workshop3@nuu
Free rtos workshop3@nuu
 
Static analysis of C++ source code
Static analysis of C++ source codeStatic analysis of C++ source code
Static analysis of C++ source code
 

Recently uploaded

Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesChandrakantDivate1
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsChandrakantDivate1
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsChandrakantDivate1
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...nishasame66
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfCWS Technology
 

Recently uploaded (6)

Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & Examples
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and Layouts
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s Tools
 
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdf
 

"Используем MetricKit в бою" / Марина Звягина (Vivid Money)

  • 1. 1
  • 3. План 3 1 MetricKit - основные сущности и как с ними работать 2 Примеры и истории из нашей практики 3 Итоги
  • 5. 5 MXMetricManager let metrikManager = MXMetricManager.shared metrikManager.add(self) open func add(_ subscriber: MXMetricManagerSubscriber) open func remove(_ subscriber: MXMetricManagerSubscriber) @available(iOS 13.0, *) open var pastPayloads: [MXMetricPayload] { get } open var pastDiagnosticPayloads: [MXDiagnosticPayload] { get } @available(iOS 14.0, *) What’s New in MetricKit
  • 6. 6 MXMetricManagerSubscriber optional func didReceive(_ payloads: [MXMetricPayload]) optional func didReceive(_ payloads: [MXDiagnosticPayload])
  • 7. MXMetricPayload includesMultipleApplicationVersions Bool latestApplicationVersion NSTaggedPointerString "1.77.0" metaData MXMetaData regionFormat NSTaggedPointerString @"RU" osVersion NSCFString @"iPhone OS 15.2 (19C56)" deviceType NSCFString @"iPhone 13,4" applicationBuildVersion NSTaggedPointerString @"1" platformArchitecture NSTaggedPointerString @"arm64e" timeStampBegin NSTaggedDate 2022-02-03 21:00:00 UTC timeStampEnd NSTaggedDate 2022-02-04 21:00:00 UTC 🤩
  • 8. MXMetricPayload applicationResponsivenessMetrics MXAppResponsivenessMetric histogrammedAppHangTime (buckets) diskIOMetrics MXDiskIOMetric cumulativeLogicalWrites "1300kB" locationActivityMetrics MXLocationActivityMetric cumulativeBestAccuracyTime "20 sec" cumulativeBastAccuracyForNavigationTime cumulativeNearestTenMetersAccuracyTime cumulativeHundredMetersAccuracyTime cumulativeKilometerAccuracyTime cumulativeThreeKilometersAccuracyTime 🤩 Improving Your App's Performance AnyHashable("applicationResponsivenessMetrics"): { histogrammedAppHangTime = { histogramNumBuckets = 3; histogramValue = { 0 = { bucketCount = 50; bucketEnd = "100 ms"; bucketStart = "0 ms"; }; 1 = { bucketCount = 60; bucketEnd = "400 ms"; bucketStart = "100 ms"; }; 2 = { bucketCount = 30; bucketEnd = "700 ms"; bucketStart = "400 ms"; }; }; }; }
  • 10. 10 @available(iOS 14.0, *) Нормальный выход Вытеснено другим приложением в foreground Переходы между стейтами занимают больше 20 секунд MXMetricPayload 🤩 cumulativeBadAccessExitCount cumulativeIllegalInstructionExitCount cumulativeAbnormalExitCount cumulativeCPUResourceLimitExitCount cumulativeMemoryResourceLimitExitCount cumulativePressureExitCount cumulativeSuspendedWithLockedFileExitCount cumulativeAppWatchdogExitCount cumulativeBackgroundTaskAssertionTimeoutExitCount cumulativeNormalExitCount Crashes Segmentation fault Illegal instruction Asserts and uncaught exceptions Understanding Crashes and Crash Logs Why is my app getting killed MXBackgroundExitData Рассмотрим вместе с MXDiagnosticPayload
  • 11. 11 MXMetricPayload 🤔 cellularConditionMetrics MXCellularConditionMetric cellConditionTime = { histogramNumBuckets = 3; histogramValue = { 0 = { bucketCount = 20; bucketEnd = "1 bars"; bucketStart = "1 bars"; }; 1 = { bucketCount = 30; bucketEnd = "2 bars"; bucketStart = "2 bars"; }; 2 = { bucketCount = 50; bucketEnd = "3 bars"; bucketStart = "3 bars"; }; }; };
  • 12. Custom Metric 12 let logHandle = MXMetricManager.makeLogHandle(category: "HomeScreen") mxSignpost(.begin, log: logHandle, name: "homeScreenLaunching") mxSignpost(.end, log: logHandle, name: "homeScreenLaunching") MXSignpostMetric histogram count mxSignpost(.event, log: logHandle, name: "homeScreenLaunching") os_signpost
  • 14. 14 MXDiagnosticPayload cpuExceptionDiagnostics: [MXCPUExceptionDiagnostic]? cpuMetrics diskWriteExceptionDiagnostics: [MXDickWriteExceptionDiagnostic]? diskIOMetrics hangDiagnostics: [MXHangDiagnostic]? applicationResponsivenessMetrics crashDiagnostics: [MXCrashDiagnostic]? applicationExitMetrics
  • 15. 15 MXCPUExceptionDiagnostic CPU Exception, or a "high CPU usage termination" 80% CPU over a period of one minute (on background execution) Why is my app getting killed Solving CPU Usage Crashes with Xcode's Energy Organizer cumulativeCPUResourceLimitExitCount Чтобы избежать этого exception'а: move work into BGProcessingTask MXBackgroundExitData
  • 16. 16 MXDiskWriteExceptionDiagnostic "diskIOMetrics": { cumulativeLogicalWrites = "1300 kB" } Генерируется, если количество записей > 1 ГБ в день "callStackTree" : { "callStacks" : [ { "callStackRootFrames" : [ { … "sampleCount" : 20 "diagnosticMetaData" : { … "regionFormat" : "GB", "writesCaused" : "2,000 byte" … } A disk write exception occurs when the app writes an excessive amount of data to the disk. diskIOMetrics MXDiskIOMetric cumulativeLogicalWrites "1300kB"
  • 18. 18 MXHangDiagnostic Eliminate animation hitches with XCTest Все данные unsymbolicated - можно использовать утилиту ATOS cd ~/Library/Developer/Xcode/Archives/2022-01-26/Vivid 26.01.2022, 20.43.xcarchive/dSYMs/Vivid.app.dSYM/Contents/Resources/DWARF/ atos -arch arm64 -o myApp 0x4329526096 Identify trends with the Power and Performance API An object representing a diagnostic report for an app that is too busy to handle user input responsively applicationResponsivenessMetrics MXAppResponsivenessMetric histogrammedAppHangTime (buckets)
  • 20. План 20 1 MetricKit - основные сущности и как с ними работать 2 Примеры и истории из нашей практики 3 Итоги ✅
  • 21. 21 reality + + In fl ux data input format Telegraf VictoriaMetrics Grafana vivid
  • 22. 22
  • 23. reality.code 23 struct PerformanceMeasure { var callTime: TimeInterval let type: PerformanceMeasureType let concreteName: String? var stopTime: TimeInterval? } struct TelegrafEvent { let name: String let time: TimeInterval let tags: [String: String] let metricType: TelegrafMetricType } let time = measure.stopTime - measure.callTime Date().timeIntervalSince1970 vivid
  • 24. 24 App launch metric func measureAppStartUpTime() -> (Double, Double) { var kinfo = kinfo_proc() var size = MemoryLayout<kinfo_proc>.stride var mib : [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()] sysctl(&mib, u_int(mib.count), &kinfo, &size, nil, 0) let startTime = kinfo.kp_proc.p_starttime var time = timeval(tv_sec: 0, tv_usec: 0) gettimeofday(&time, nil) let currentTimeMilliseconds = (Double(Int64(time.tv_sec) * 1_000) + Double(time.tv_usec) / 1_000.0) / 1_000.0 let processTimeMilliseconds = (Double(Int64(startTime.tv_sec) * 1_000) + Double(startTime.tv_usec) / 1_000.0) / 1_000.0 return (processTimeMilliseconds, currentTimeMilliseconds) } vivid
  • 25. 25
  • 26. 26 MetricKit @available(iOS 13.0, *) func didReceive(_ payloads: [MXMetricPayload]) { payloads.forEach { payload in print(payload.dictionaryRepresentation()) var currentSaveValues: [String] = payloadsStored.get() ?? [] currentSaveValues.append("MXMetricPayload = (payload.dictionaryRepresentation().description)") payloadsStored.set(value: currentSaveValues) let firstDrawBuckets: [MXHistogramBucket] = (payload.applicationLaunchMetrics?.histogrammedTimeToFirstDraw.bucketEnumerator.allObjects as? [MXHistogramBucket<Unit>]) .rescue([]) firstDrawBuckets.forEach { bucket in addMetricsIfNeeded(bucket: bucket, measureType: .appLaunchMetricsTime) } let resumeBackets: [MXHistogramBucket] = (payload.applicationLaunchMetrics?.histogrammedApplicationResumeTime.bucketEnumerator.allObjects as? [MXHistogramBucket<Unit>]) .rescue([]) resumeBackets.forEach { bucket in addMetricsIfNeeded(bucket: bucket, measureType: .appResumeMetricsTime) } } } vivid
  • 27. 27
  • 28. 28 struct PerformanceNewMeasure { var callTime: TimeInterval let type: PerformanceMeasureType let concreteName: String? var stopTime: TimeInterval? } struct TelegrafEvent { let name: String let time: TimeInterval let tags: [String: String] let metricType: TelegrafMetricType } let time = measure.stopTime - measure.callTime Date().timeIntervalSince1970 Date().timeIntervalSince1970 event.time.multiply(1_000) Ответ Date().timeIntervalSince1970 vivid reality.code
  • 29. 29 histogrammedTimeToFirstDrawKey = { histogramNumBuckets = 3; histogramValue = { 0 = { bucketCount = 50; bucketEnd = "1010 ms"; bucketStart = "1000 ms"; }; 1 = { bucketCount = 60; bucketEnd = "2010 ms"; bucketStart = "2000 ms"; }; 2 = { bucketCount = 30; bucketEnd = "3010 ms"; bucketStart = "3000 ms"; }; }; }; "time_obtain_short_i,name=BeforeApp,env=stable,ver=1.77.0 ms=682.904005050659" vivid reality.code
  • 30. 30 @available(iOS 13.0, *) func addMetricsIfNeeded(bucket: MXHistogramBucket<Unit>, measureType: PerformanceMeasureType) { let bucketEnd = bucket.bucketEnd let bucketStart = bucket.bucketStart let countOfEvents = bucket.bucketCount if bucketEnd.unit.symbol == "ms" && bucketStart.unit.symbol == "ms" { let averageValue = (bucketEnd.value.plus(bucketStart.value)) / 2 let appLaunchEvent = performanceTracker.getEvent(with: .fastRequestLoading) guard countOfEvents > 0 else { return } for _ in 1...countOfEvents { appLaunchEvent.addMeasure(callTime: 0, stopTime: averageValue, measureType: measureType, kind: .simple) } } } vivid reality.code
  • 32. План 32 1 MetricKit - основные сущности и как с ними работать 2 Примеры и истории из нашей практики 3 Итоги ✅ ✅
  • 33. 33 💚 MetricKit легко добавить 💚 MetricKit можно использовать вместе с остальными метриками, но есть 2 нюанса: - Нужно учитывать, в каком они формате (их 3 - бакеты, количество и длительность) - Следить за единицами измерения 💚 Удобно использовать метрики в связке с Pro fi ler и с Organizer - они позволяют смотреть в моменте и регресс, а MetricKit позволяет смотреть в динамике от сборки к сборке 💚 Сопоставление MXMetricPayload vs MXDiagnosticPayload ❌ MXDiagnostic не доступен без dSYMs - не получится в реальном времени отслеживать данные ❌ Не все метрики кажутся полезными ❌ Perf tests Итоги
  • 34. MetricKit What’s New in MetricKit Improving Your App's Performance Understanding Crashes and Crash Logs Why is my app getting killed Solving CPU Usage Crashes with Xcode's Energy Organizer Eliminate animation hitches with XCTest Identify trends with the Power and Performance API Telegraf VictoriaMetrics Grafana https://stackoverflow.com/questions/64378095/metrickit-mxdiagnostic-symbolication https://swiftrocks.com/debug-cpu-exceptions-xcode-energy-reports https://medium.com/naukri-engineering/overview-of-dsym-crashlytics-in-ios-dfd72eae8b58 iOS Performance Engineer Android Performance Engineer https://jobs.vivid.money/jobs/Careers/33579000004386184/iOS-developer-Performance-team-?source=CareerSite https://jobs.vivid.money/jobs/Careers/33579000004386170/Android-developer-Performance-team-?source=CareerSite