Last active
February 12, 2019 14:54
-
-
Save drumnkyle/37665e4534cd5b7609d7b4592b10b603 to your computer and use it in GitHub Desktop.
Full Scroll Performance Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The MIT License | |
Copyright (c) 2010-2018 Google, Inc. http://angularjs.org | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. | |
*/ | |
#import <Foundation/Foundation.h> | |
/** | |
These methods will not be called on the main thread. So, | |
if you will be doing anything with UIKit, ensure you dispatch back | |
to the main thread. | |
*/ | |
@protocol KSScrollPerformanceDetectorDelegate<NSObject> | |
@optional | |
- (void)framesDropped:(NSInteger)framesDroppedCount cumulativeFramesDropped:(NSInteger)cumulativeFramesDropped cumulativeFrameDropEvents:(NSInteger)cumulativeFrameDropEvents; | |
@end | |
@interface KSScrollPerformanceDetector : NSObject | |
@property(nonatomic, assign, readonly) NSInteger currentFrameDropCount; | |
@property(nonatomic, assign, readonly) NSInteger currentFrameDropEventCount; | |
@property(nonatomic, weak, nullable) id<KSScrollPerformanceDetectorDelegate> delegate; | |
- (nonnull instancetype)init NS_DESIGNATED_INITIALIZER; | |
- (void)resume; | |
- (void)pause; | |
- (void)clearFrameDropCount; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The MIT License | |
Copyright (c) 2010-2018 Google, Inc. http://angularjs.org | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. | |
*/ | |
#import "KSScrollPerformanceDetector.h" | |
#import <UIKit/UIKit.h> | |
@interface KSScrollPerformanceDetector() | |
@property(nonatomic, strong, nonnull) CADisplayLink *displayLink; | |
@property(nonatomic, assign, readwrite) CFTimeInterval lastTimestamp; | |
@property(nonatomic, assign, readwrite) NSInteger currentFrameDropCount; | |
@property(nonatomic, assign, readwrite) NSInteger currentFrameDropEventCount; | |
@property(nonatomic, strong, nonnull) dispatch_queue_t workerQueue; | |
- (void)displayLinkTriggered:(CADisplayLink *)sender; | |
- (void)calculateFrameDropForNumberOfFrames:(NSInteger)numberOfFrames; | |
- (void)registerLifecyleNotifications; | |
@end | |
@implementation KSScrollPerformanceDetector | |
#pragma mark - Initializers | |
- (instancetype)init { | |
self = [super init]; | |
[self registerLifecyleNotifications]; | |
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkTriggered:)]; | |
_displayLink.paused = YES; | |
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; | |
_lastTimestamp = 0; | |
dispatch_queue_attr_t attributes = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, DISPATCH_QUEUE_PRIORITY_HIGH); | |
_workerQueue = dispatch_queue_create("com.frame-rate-reporter.worker", attributes); | |
return self; | |
} | |
#pragma mark - Public Methods | |
- (void)clearFrameDropCount { | |
__weak typeof(self) weakSelf = self; | |
dispatch_async(self.workerQueue, ^{ | |
typeof(self) strongSelf = weakSelf; | |
if (!strongSelf) { | |
return; | |
} | |
self->_currentFrameDropCount = 0; | |
self->_currentFrameDropEventCount = 0; | |
}); | |
} | |
- (void)resume { | |
self.displayLink.paused = NO; | |
} | |
- (void)pause { | |
self.displayLink.paused = YES; | |
} | |
#pragma mark - Private Methods | |
#pragma mark Lifecyle | |
- (void)registerLifecyleNotifications { | |
[[NSNotificationCenter defaultCenter] addObserver:self | |
selector:@selector(notifyActivate:) | |
name:UIApplicationDidBecomeActiveNotification | |
object:nil]; | |
[[NSNotificationCenter defaultCenter] addObserver:self | |
selector:@selector(notifyDeactivate:) | |
name:UIApplicationWillResignActiveNotification | |
object:nil]; | |
} | |
- (void)notifyActivate:(NSNotification *)notification { | |
self.displayLink.paused = NO; | |
self.lastTimestamp = 0; | |
} | |
- (void)notifyDeactivate:(NSNotification *)notification { | |
self.displayLink.paused = YES; | |
} | |
- (void)dealloc { | |
[[NSNotificationCenter defaultCenter] removeObserver:self]; | |
self.displayLink.paused = YES; | |
[self.displayLink invalidate]; | |
} | |
#pragma mark Calculations | |
- (void)displayLinkTriggered:(CADisplayLink *)sender { | |
dispatch_async(self.workerQueue, ^{ | |
if (self.lastTimestamp == 0) { | |
self.lastTimestamp = sender.timestamp; | |
return; | |
} | |
CFTimeInterval duration = sender.duration; | |
if (duration == 0) { | |
return; | |
} | |
double numberOfFramesDouble = round((sender.timestamp - self.lastTimestamp) / duration); | |
NSAssert(numberOfFramesDouble <= NSIntegerMax && numberOfFramesDouble >= NSIntegerMin, @"fps double value out of range of NSInteger"); | |
NSInteger numberOfFrames = numberOfFramesDouble; | |
self.lastTimestamp = sender.timestamp; | |
[self calculateFrameDropForNumberOfFrames:numberOfFrames]; | |
}); | |
} | |
- (void)calculateFrameDropForNumberOfFrames:(NSInteger)numberOfFrames { | |
NSInteger droppedFrameCount = numberOfFrames - 1 > 0 ? numberOfFrames : 0; | |
self.currentFrameDropCount += droppedFrameCount; | |
if (droppedFrameCount > 0) { | |
self.currentFrameDropEventCount += 1; | |
} | |
if (droppedFrameCount > 0 && | |
self.listener && | |
[self.delegate respondsToSelector:@selector(framesDropped:cumulativeFramesDropped:cumulativeFrameDropEvents:)]) { | |
[self.delegate framesDropped:droppedFrameCount | |
cumulativeFramesDropped:self.currentFrameDropCount | |
cumulativeFrameDropEvents:self.currentFrameDropEventCount]; | |
} | |
} | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The MIT License | |
Copyright (c) 2010-2018 Google, Inc. http://angularjs.org | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. | |
*/ | |
#ifndef usage_h | |
#define usage_h | |
#import <mach/mach.h> | |
double cpu_usage(int64_t *count); | |
float mem_usage(); | |
#endif /* usage_h */ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The MIT License | |
Copyright (c) 2010-2018 Google, Inc. http://angularjs.org | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. | |
*/ | |
#import <mach/mach.h> | |
#import "usage.h" | |
double cpu_usage(int64_t *count) | |
{ | |
kern_return_t kr; | |
task_info_data_t tinfo; | |
mach_msg_type_number_t task_info_count; | |
task_info_count = TASK_INFO_MAX; | |
kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count); | |
if (kr != KERN_SUCCESS) { | |
return -1; | |
} | |
task_basic_info_t basic_info; | |
thread_array_t thread_list; | |
mach_msg_type_number_t thread_count; | |
thread_info_data_t thinfo; | |
mach_msg_type_number_t thread_info_count; | |
thread_basic_info_t basic_info_th; | |
uint32_t stat_thread = 0; | |
basic_info = (task_basic_info_t)tinfo; | |
kr = task_threads(mach_task_self(), &thread_list, &thread_count); | |
if (kr != KERN_SUCCESS) { | |
return -1; | |
} | |
if (thread_count > 0) | |
stat_thread += thread_count; | |
long tot_sec = 0; | |
long tot_usec = 0; | |
double tot_cpu = 0; | |
uint j; | |
for (j = 0; j < thread_count; j++) | |
{ | |
thread_info_count = THREAD_INFO_MAX; | |
kr = thread_info(thread_list[j], THREAD_BASIC_INFO, | |
(thread_info_t)thinfo, &thread_info_count); | |
if (kr != KERN_SUCCESS) { | |
return -1; | |
} | |
basic_info_th = (thread_basic_info_t)thinfo; | |
if (!(basic_info_th->flags & TH_FLAGS_IDLE)) { | |
tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds; | |
tot_usec = tot_usec + basic_info_th->user_time.microseconds + basic_info_th->system_time.microseconds; | |
tot_cpu = tot_cpu + basic_info_th->cpu_usage / (double)TH_USAGE_SCALE * 100.0; | |
} | |
} | |
kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t)); | |
if (count) { | |
*count = thread_count; | |
} | |
return tot_cpu; | |
} | |
float mem_usage() | |
{ | |
struct mach_task_basic_info info; | |
mach_msg_type_number_t size = MACH_TASK_BASIC_INFO_COUNT; | |
kern_return_t kerr = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &size); | |
return ( kerr == KERN_SUCCESS ) ? info.resident_size : 0; | |
} |
swift translation of KSScrollPerformanceDetector
:
import Foundation
public protocol KSScrollPerformanceDetectorDelegate: NSObjectProtocol {
func framesDropped(count: Int, cumulativeCount: Int, cumulativeEventsCount: Int)
}
public class KSScrollPerformanceDetector: NSObject {
public private(set) var currentFrameDropCount: Int
public private(set) var currentFrameDropEventCount: Int
public weak var delegate: KSScrollPerformanceDetectorDelegate?
internal var lastTimestamp: CFTimeInterval
internal var workerQueue: DispatchQueue
internal lazy var displayLink: CADisplayLink = {
let link = CADisplayLink(target: self, selector: #selector(displayLinkTriggered(_:)))
link.isPaused = true
link.add(to: RunLoop.main, forMode: .common)
return link
}()
public override init() {
self.lastTimestamp = 0
self.workerQueue = DispatchQueue(label: "com.frame-rate-reporter.worker", qos: .userInitiated, attributes: .concurrent)
self.currentFrameDropCount = 0
self.currentFrameDropEventCount = 0
super.init()
self.registerLifecyleNotifications()
}
deinit {
NotificationCenter.default.removeObserver(self)
self.displayLink.isPaused = true
self.displayLink.invalidate()
}
// Mark: init helpers
internal func registerLifecyleNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(notifyActivate(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(notifyDeactivate(_:)), name: UIApplication.willResignActiveNotification, object: nil)
}
// Mark: Public methods
public func resume() {
self.displayLink.isPaused = false
}
public func pause() {
self.displayLink.isPaused = true
}
public func clearFrameRate() {
self.workerQueue.async { [weak self] in
guard let self = self else { return }
self.currentFrameDropCount = 0
self.currentFrameDropEventCount = 0
}
}
//Mark: private methods
@objc internal func displayLinkTriggered(_ sender: CADisplayLink) {
self.workerQueue.async {
guard sender.duration != 0 else { return }
defer { self.lastTimestamp = sender.timestamp }
guard self.lastTimestamp != 0 else { return }
let numberOfFramesDouble = round((sender.timestamp - self.lastTimestamp)/sender.duration)
assert(numberOfFramesDouble <= Double(Int.max) && numberOfFramesDouble >= Double(Int.min))
let numberOfFrames = Int(numberOfFramesDouble)
self.calculateFrameDrop(for: numberOfFrames)
}
}
internal func calculateFrameDrop(for numberOfFrames: Int) {
let droppedFrameCount = numberOfFrames - 1 > 0 ? numberOfFrames : 0 // pretty sure that could just be max(numberOfFrames, 0)
guard droppedFrameCount > 0 else { return }
self.currentFrameDropCount += droppedFrameCount
self.currentFrameDropEventCount += 1
self.delegate?.framesDropped(count: droppedFrameCount, cumulativeCount: self.currentFrameDropCount, cumulativeEventsCount: self.currentFrameDropEventCount)
}
@objc internal func notifyActivate(_ notification: NSNotification) {
self.resume()
self.lastTimestamp = 0
}
@objc internal func notifyDeactivate(_ notification: NSNotification) {
self.pause()
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
KSScrollPerformanceDetector.m: does not compile:
Remove:
self.listener &&
in line #138