iOS - 如何找出哪个方法占用了这么多时间

iOS - How To Find Which Method Is Taking Up So Much Time

在我的应用程序中,用户可以 "speed-read" 通过让文字以他们设定的速度在屏幕上闪烁来发短信。我已经在我的 UIViewController 中使用重复 NSTimer 并通过显示下一个单词索引更新 UILabel 来编写此功能,但速度没有达到应有的速度。

例如,我以每分钟 1000 字的速度测试了 100 字。完成闪烁所有单词需要 6.542045,而不是应该花费 6 秒。这是一个大问题,因为我应该向用户反馈他们阅读文本所花费的时间。

如何找出代码的哪一部分花费了这么长时间?是 UILabel 的更新占用了 0.54~~ 的时间吗?

编辑

我的示例项目可以在这里查看:https://github.com/cnowak7/RSVPTesting

我的flashText方法应该只触发100次。好吧,如果我们计算方法意识到没有更多单词并终止 NSTimer 的时间,则为 101。在控制台中,阅读结束时,我可以看到该方法被触发了 111 次。我想我可能做错了。

您的具体问题似乎是:How do I find out what part of the code is taking so long? Is it the updating of the UILabel that's eating up 0.54~~ of the time?

Inside Instruments 随 Xcode 提供,是一个 Time Profiler 工具。 https://developer.apple.com/library/ios/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/Instrument-TimeProfiler.html

您可以 运行 您的代码并观察此工具,以准确了解执行例程的每个部分所花费的时间。它将按总时间百分比和具体时间跨度准确细分哪种方法花费的时间最多,让您准确了解应该将精力集中在哪里以通过 refactoring/optimizations 削减那些宝贵的部分秒数。

我是一个 Objective-C 的人,所以与其试图在 Swift 的例子中蒙混过关,不如让这个人来说话。 https://www.raywenderlich.com/97886/instruments-tutorial-with-swift-getting-started

每当您想了解 iOS 中的时间消耗时,您应该总是去 Instruments and select time profiler as shown in the image.

时间分析器将帮助您找到占用过多时间的代码。