如何在Ruby中检测哈希数组里并发运行的测试用例
找出并发运行的测试实现方案
预处理测试数据
首先我们需要给每个测试补充计算好的开始、结束时间戳,同时过滤掉空哈希这类无效数据:
# 预处理所有测试,添加开始/结束时间戳并过滤空项 processed_tests = all_tests.reject(&:empty?).map do |test| start_ts = test['TimeStamp'].to_i end_ts = start_ts + test['duration'] test.merge('start_ts' => start_ts, 'end_ts' => end_ts) end.compact
方法一:两两比对(适合小数据量)
遍历每个测试,与其他测试逐一比对时间区间,只要存在重叠就标记为并发测试:
concurrent_tests = [] processed_tests.each_with_index do |test_a, idx_a| next if concurrent_tests.include?(test_a) # 跳过已标记的测试,避免重复 # 判断当前测试是否存在并发对象 has_concurrent = processed_tests.each_with_index.any? do |test_b, idx_b| next if idx_a == idx_b # 跳过自身比对 # 时间区间重叠判断逻辑:test_a启动时test_b未结束,且test_a结束时test_b已启动 test_a['start_ts'] < test_b['end_ts'] && test_a['end_ts'] > test_b['start_ts'] end concurrent_tests << test_a if has_concurrent end
方法二:排序后检测(高效适合大数据量)
先按开始时间戳排序,再遍历检测当前测试与前一个测试是否重叠,同时收集所有涉及并发的测试:
# 按开始时间戳排序测试列表 sorted_tests = processed_tests.sort_by { |t| t['start_ts'] } concurrent_tests = [] previous_test = nil sorted_tests.each do |current_test| if previous_test && current_test['start_ts'] < previous_test['end_ts'] # 将两个并发测试加入数组(自动去重) concurrent_tests << previous_test unless concurrent_tests.include?(previous_test) concurrent_tests << current_test unless concurrent_tests.include?(current_test) end previous_test = current_test end
关键说明
- 时间区间重叠的判断逻辑
test_a['start_ts'] < test_b['end_ts'] && test_a['end_ts'] > test_b['start_ts']可以覆盖所有并发场景,包括一个测试完全包含另一个测试的情况 - 预处理步骤过滤了空哈希,避免处理无效数据
- 两种方法都不会修改原始的
all_tests数组,而是基于预处理后的新数组操作
内容的提问来源于stack exchange,提问作者Rubin
相关产品推荐
相关产品推荐

