Skip to content

Commit 1d3fa87

Browse files
committed
[benchmark] Strangle log_results -> log_file
Moved the `log_file` path construction to the `BenchmarkDriver`. Retired `get_*_git_*` functions.
1 parent 049ffb3 commit 1d3fa87

File tree

2 files changed

+68
-52
lines changed

2 files changed

+68
-52
lines changed

benchmark/scripts/Benchmark_Driver

Lines changed: 34 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,28 @@ class BenchmarkDriver(object):
6767
else 'O')
6868
return os.path.join(self.args.tests, "Benchmark_" + suffix)
6969

70+
def _git(self, cmd):
71+
"""Execute the Git command in the `swift-repo`."""
72+
return self._invoke(
73+
('git -C {0} '.format(self.args.swift_repo) + cmd).split()).strip()
74+
75+
@property
76+
def log_file(self):
77+
"""Full path to log file.
78+
79+
If `swift-repo` is set, log file is tied to Git branch and revision.
80+
"""
81+
if not self.args.output_dir:
82+
return None
83+
log_dir = self.args.output_dir
84+
harness_name = os.path.basename(self.test_harness)
85+
suffix = '-' + time.strftime('%Y%m%d%H%M%S', time.localtime())
86+
if self.args.swift_repo:
87+
log_dir = os.path.join(
88+
log_dir, self._git('rev-parse --abbrev-ref HEAD')) # branch
89+
suffix += '-' + self._git('rev-parse --short HEAD') # revision
90+
return os.path.join(log_dir, harness_name + suffix + '.log')
91+
7092
@property
7193
def _cmd_list_benchmarks(self):
7294
# Use tab delimiter for easier parsing to override the default comma.
@@ -377,52 +399,17 @@ class BenchmarkDoctor(object):
377399
return 0
378400

379401

380-
def get_current_git_branch(git_repo_path):
381-
"""Return the selected branch for the repo `git_repo_path`"""
382-
return subprocess.check_output(
383-
['git', '-C', git_repo_path, 'rev-parse',
384-
'--abbrev-ref', 'HEAD'], stderr=subprocess.STDOUT).strip()
385-
386-
387-
def get_git_head_ID(git_repo_path):
388-
"""Return the short identifier for the HEAD commit of the repo
389-
`git_repo_path`"""
390-
return subprocess.check_output(
391-
['git', '-C', git_repo_path, 'rev-parse',
392-
'--short', 'HEAD'], stderr=subprocess.STDOUT).strip()
393-
394-
395-
def log_results(log_directory, driver, formatted_output, swift_repo=None):
396-
"""Log `formatted_output` to a branch specific directory in
397-
`log_directory`
398-
"""
399-
try:
400-
branch = get_current_git_branch(swift_repo)
401-
except (OSError, subprocess.CalledProcessError):
402-
branch = None
403-
try:
404-
head_ID = '-' + get_git_head_ID(swift_repo)
405-
except (OSError, subprocess.CalledProcessError):
406-
head_ID = ''
407-
timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
408-
if branch:
409-
output_directory = os.path.join(log_directory, branch)
410-
else:
411-
output_directory = log_directory
412-
driver_name = os.path.basename(driver)
402+
def log_results(log_file, formatted_output):
413403
try:
414-
os.makedirs(output_directory)
404+
os.makedirs(os.path.dirname(log_file))
415405
except OSError:
416406
pass
417-
log_file = os.path.join(output_directory,
418-
driver_name + '-' + timestamp + head_ID + '.log')
419407
print('Logging results to: %s' % log_file)
420408
with open(log_file, 'w') as f:
421409
f.write(formatted_output)
422410

423411

424-
def run_benchmarks(driver,
425-
log_directory=None, swift_repo=None):
412+
def run_benchmarks(driver):
426413
"""Run perf tests individually and return results in a format that's
427414
compatible with `LogParser`.
428415
"""
@@ -433,11 +420,12 @@ def run_benchmarks(driver,
433420
# that runs the tests.
434421
os.environ["SWIFT_DETERMINISTIC_HASHING"] = "1"
435422

423+
log = driver.log_file
436424
output = []
437425
headings = ['#', 'TEST', 'SAMPLES', 'MIN(μs)', 'MAX(μs)', 'MEAN(μs)',
438426
'SD(μs)', 'MEDIAN(μs)', 'MAX_RSS(B)']
439427
line_format = '{:>3} {:<25} {:>7} {:>7} {:>7} {:>8} {:>6} {:>10} {:>10}'
440-
if log_directory:
428+
if log:
441429
print(line_format.format(*headings))
442430
else:
443431
print(','.join(headings))
@@ -446,7 +434,7 @@ def run_benchmarks(driver,
446434
test_output = map(str, [
447435
r.test_num, r.name, r.num_samples, r.min, r.max, int(r.mean),
448436
int(r.sd), r.median, r.max_rss])
449-
if log_directory:
437+
if log:
450438
print(line_format.format(*test_output))
451439
else:
452440
print(','.join(test_output))
@@ -456,22 +444,18 @@ def run_benchmarks(driver,
456444
formatted_output = '\n'.join([','.join(l) for l in output])
457445
totals = ['Totals', str(len(driver.tests))]
458446
totals_output = '\n\n' + ','.join(totals)
459-
if log_directory:
447+
if log:
460448
print(line_format.format(*([''] + totals + ([''] * 6))))
461449
else:
462450
print(totals_output[1:])
463451
formatted_output += totals_output
464-
if log_directory:
465-
log_results(log_directory, driver.test_harness, formatted_output,
466-
swift_repo)
452+
if log:
453+
log_results(log, formatted_output)
467454
return formatted_output
468455

469456

470457
def run(args):
471-
run_benchmarks(
472-
BenchmarkDriver(args),
473-
log_directory=args.output_dir,
474-
swift_repo=args.swift_repo)
458+
run_benchmarks(BenchmarkDriver(args))
475459
return 0
476460

477461

@@ -491,10 +475,10 @@ def compare_logs(compare_script, new_log, old_log, log_dir, opt):
491475

492476
def compare(args):
493477
log_dir = args.log_dir
494-
swift_repo = args.swift_repo
495478
compare_script = args.compare_script
496479
baseline_branch = args.baseline_branch
497-
current_branch = get_current_git_branch(swift_repo)
480+
current_branch = \
481+
BenchmarkDriver(args, tests=[''])._git('rev-parse --abbrev-ref HEAD')
498482
current_branch_dir = os.path.join(log_dir, current_branch)
499483
baseline_branch_dir = os.path.join(log_dir, baseline_branch)
500484

benchmark/scripts/test_Benchmark_Driver.py

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
import logging
1717
import os
18+
import time
1819
import unittest
1920

2021
from imp import load_source
@@ -106,6 +107,11 @@ def test_iterations(self):
106107
"argument -i/--iterations: invalid positive_int value: '-3'"],
107108
err.getvalue())
108109

110+
def test_output_dir(self):
111+
self.assertIsNone(parse_args(['run']).output_dir)
112+
self.assertEquals(
113+
parse_args(['run', '--output-dir', '/log']).output_dir, '/log')
114+
109115
def test_check_supports_vebose_output(self):
110116
self.assertFalse(parse_args(['check']).verbose)
111117
self.assertTrue(parse_args(['check', '-v']).verbose)
@@ -125,7 +131,7 @@ class SubprocessMock(Mock):
125131
STDOUT = object()
126132

127133
def __init__(self, responses=None):
128-
super(SubprocessMock, self).__init__()
134+
super(SubprocessMock, self).__init__(responses)
129135

130136
def _check_output(args, stdin=None, stdout=None, stderr=None,
131137
shell=False):
@@ -196,6 +202,32 @@ def test_filters_benchmarks_by_pattern(self):
196202
self.assertEquals(driver.all_tests,
197203
['Benchmark1', 'Benchmark2', 'Benchmark3'])
198204

205+
def test_log_file(self):
206+
"""When swift-repo is set, log is tied to Git branch and revision."""
207+
self.assertIsNone(BenchmarkDriver(
208+
Stub(output_dir=None, tests='/bin/'), tests=['ignored']).log_file)
209+
210+
now = time.strftime('%Y%m%d%H%M%S', time.localtime())
211+
driver = BenchmarkDriver(
212+
Stub(output_dir='/path', tests='/bin/', optimization='Suffix',
213+
swift_repo=None,), tests=['ignored'])
214+
self.assertEquals(driver.log_file,
215+
'/path/Benchmark_Suffix-' + now + '.log')
216+
217+
r = '/repo/'
218+
subprocess_mock = SubprocessMock(responses=[
219+
('git -C {0} rev-parse --abbrev-ref HEAD'.format(r).split(' '),
220+
'branch\n'),
221+
('git -C {0} rev-parse --short HEAD'.format(r).split(' '),
222+
'short_hash\n'),
223+
])
224+
driver = BenchmarkDriver(
225+
Stub(output_dir='/log/', tests='', optimization='S', swift_repo=r),
226+
tests=['ignored'], _subprocess=subprocess_mock)
227+
self.assertEquals(driver.log_file,
228+
'/log/branch/Benchmark_S-' + now + '-short_hash.log')
229+
subprocess_mock.assert_called_all_expected()
230+
199231

200232
class LogParserStub(object):
201233
results_from_string_called = False
@@ -258,7 +290,7 @@ def mock_run(test):
258290
self.assertEquals(test, 'b1')
259291
return PerformanceTestResult(
260292
'3,b1,1,123,123,123,0,123,888'.split(','))
261-
driver = Stub(tests=['b1'])
293+
driver = Stub(tests=['b1'], log_file=None)
262294
driver.run_independent_samples = mock_run
263295
run_benchmarks = Benchmark_Driver.run_benchmarks
264296

0 commit comments

Comments
 (0)