如果性能测试太慢,性能测试会失败吗?

问题描述:

如果运行速度低于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)") 
} 

测试数据

[Tests.ParserTest testParticipantCodeParsingPerformance]”测量[时间,秒]平均值:0.203,相对标准偏差:19.951%,值: [0.186405,0.182292,0.1179966,0.1777797,0.1175820,0.205763,0.315636,0.223014,0.200362,0.178165]

您需要为性能测试设置基准。头向报告导航:

Report Navigator

,并选择您最近的测试运行。您会看到所有测试的列表,但表现的测试将与其关联。点击时,弹出性能结果酥料饼:

Performance Result

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

+1

这些工作得很好,但他们只在我的机器上本地工作,我使用Git为我的项目和所有其他用户没有设置基线。有没有办法在git项目中包含这个基线? – Deco

+0

我发现这个做了这个工作 https://*.com/a/46563991/957245 – Deco

执行类似于您所描述的操作的唯一方法是像@ 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() 
    }) 
}