【问题标题】:How to make a performance test fail if it's too slow?如果太慢,如何使性能测试失败?
【发布时间】:2016-11-17 10:54:04
【问题描述】:

如果运行速度低于 0.5 秒,我希望我的测试失败,但平均时间只是打印在控制台中,我找不到访问它的方法。有没有办法访问这些数据?

代码

//Measures the time it takes to parse the participant codes from the first 100 events in our test data.
func testParticipantCodeParsingPerformance()
{
    var increment = 0
    self.measureBlock
    {
        increment = 0
        while increment < 100
        {
            Parser.parseParticipantCode(self.fields[increment], hostCodes: MasterCalendarArray.getHostCodeArray()[increment])
            increment++
        }
    }
    print("Events measured: \(increment)")
}

测试数据

[Test.Parsertest TestParticiPantCodeParsingPerformance]'测量[时间,秒]平均:0.203,相对标准偏差:19.951%,值:[0.186405,0.182292,0.179966,0.179966,0.179966,0.179966,0.17966,0.179966,0.179966,0.179966,0.179966,0.179966,0.17966,0.177797,0.175820,0.20576,0.315636,0.223014,0.200362,0.178165]

【问题讨论】:

    标签: ios swift performance performance-testing


    【解决方案1】:

    与您描述的类似的唯一方法是像@andyvn22 建议的那样以图形方式设置时间限制。

    但是,如果你想完全在代码中完成它,你唯一能做的就是使用一个新方法扩展 XCTestCase,该方法测量闭包的执行时间并将其返回以用于断言,这里是一个例子你能做什么:

    extension XCTestCase{
        /// Executes the block and return the execution time in millis
        public func timeBlock(closure: ()->()) -> Int{
            var info = mach_timebase_info(numer: 0, denom: 0)
            mach_timebase_info(&info)
            let begin = mach_absolute_time()
    
            closure()
    
            let diff = Double(mach_absolute_time() - begin) * Double(info.numer) / Double(1_000_000 * info.denom)
            return Int(diff)
        }
    }
    

    并将其用于:

    func testExample() {
        XCTAssertTrue( 500 < self.timeBlock{
            doSomethingLong()
        })
    }
    

    【讨论】:

      【解决方案2】:

      您需要为性能测试设置基线。前往报告导航器:

      并选择您最近的测试运行。您将看到所有测试的列表,但性能测试将与它们相关联。点击时间弹出 Performance Result 弹窗:

      “基线”值是您要查找的值 - 将其设置为 0.5 秒,这将通知 Xcode 该测试应该在半秒内完成。如果你的测试比基线慢 10% 以上,它就会失败!

      【讨论】:

      • 这些运行良好,但它们只能在我的机器上本地运行,我在我的项目中使用 git,所有其他用户都没有设置他们的基线。有没有办法在 git 项目中包含这个基线?
      猜你喜欢
      • 2014-01-05
      • 2020-08-14
      • 1970-01-01
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多