Skip to content

Commit 82c3693

Browse files
committed
misc: Lint benchmarks
1 parent 8d0c325 commit 82c3693

4 files changed

Lines changed: 36 additions & 31 deletions

File tree

benchmarks/regression/benchmarks/arguments.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ class Processing:
1010
def setup(self):
1111
grid = Grid(shape=(5, 5, 5))
1212

13-
funcs = [Function(name='f%d' % n, grid=grid) for n in range(30)]
14-
tfuncs = [TimeFunction(name='u%d' % n, grid=grid) for n in range(30)]
15-
stfuncs = [SparseTimeFunction(name='su%d' % n, grid=grid, npoint=1, nt=100)
13+
funcs = [Function(name=f'f{n}', grid=grid) for n in range(30)]
14+
tfuncs = [TimeFunction(name=f'u{n}', grid=grid) for n in range(30)]
15+
stfuncs = [SparseTimeFunction(name=f'su{n}', grid=grid, npoint=1, nt=100)
1616
for n in range(30)]
1717
v = TimeFunction(name='v', grid=grid, space_order=2)
1818

benchmarks/user/advisor/run_advisor.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,7 @@ def run_with_advisor(path, output, name, exec_args):
140140
advixe_logger.setLevel(logging.INFO)
141141

142142
advixe_formatter = logging.Formatter('%(asctime)s: %(message)s')
143-
logger_datetime = '%d.%d.%d.%d.%d.%d' % (dt.year, dt.month,
144-
dt.day, dt.hour, dt.minute, dt.second)
143+
logger_datetime = f'{dt.year}.{dt.month}.{dt.day}.{dt.hour}.{dt.minute}.{dt.second}'
145144
advixe_handler = logging.FileHandler(f'{output}/{name}_{logger_datetime}.log')
146145
advixe_handler.setFormatter(advixe_formatter)
147146
advixe_logger.addHandler(advixe_handler)

benchmarks/user/benchmark.py

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
from contextlib import suppress
23

34
import click
45
import numpy as np
@@ -73,8 +74,10 @@ def run_op(solver, operator, **options):
7374
# Get the operator if exist
7475
try:
7576
op = getattr(solver, operator)
76-
except AttributeError:
77-
raise AttributeError(f"Operator {operator} not implemented for {solver}")
77+
except AttributeError as e:
78+
raise AttributeError(
79+
f"Operator {operator} not implemented for {solver}"
80+
) from e
7881

7982
# This is a bit ugly but not sure how to make clean input creation for different op
8083
if operator == "forward":
@@ -164,7 +167,10 @@ def from_opt(ctx, param, value):
164167
# E.g. `'advanced'`
165168
opt = value
166169
if opt not in configuration._accepted['opt']:
167-
raise click.BadParameter("Invalid choice `{}` (choose from {})".format(opt, str(configuration._accepted['opt'])))
170+
raise click.BadParameter(
171+
f'Invalid choice `{opt} '
172+
f'(choose from {str(configuration._accepted["opt"])})'
173+
)
168174
return value
169175

170176
def config_blockshape(ctx, param, value):
@@ -180,7 +186,7 @@ def config_blockshape(ctx, param, value):
180186
# 1. integers, not strings
181187
# 2. sanity check the (hierarchical) blocking shape
182188
normalized_value = []
183-
for i, block_shape in enumerate(value):
189+
for block_shape in value:
184190
# If hierarchical blocking is activated, say with N levels, here in
185191
# `bs` we expect to see 3*N entries
186192
bs = [int(x) for x in block_shape.split()]
@@ -204,7 +210,10 @@ def config_autotuning(ctx, param, value):
204210
elif value != 'off':
205211
# Sneak-peek at the `block-shape` -- if provided, keep auto-tuning off
206212
if ctx.params['block_shape']:
207-
warning("Skipping autotuning (using explicit block-shape `{}`)".format(str(ctx.params['block_shape'])))
213+
warning(
214+
'Skipping autotuning'
215+
f'(using explicit block-shape `{str(ctx.params["block_shape"])}`)'
216+
)
208217
level = False
209218
else:
210219
# Make sure to always run in preemptive mode
@@ -272,8 +281,8 @@ def run(problem, **kwargs):
272281
# Note: the following piece of code is horribly *hacky*, but it works for now
273282
for i, block_shape in enumerate(block_shapes):
274283
for n, level in enumerate(block_shape):
275-
for d, s in zip(['x', 'y', 'z'], level):
276-
options['%s%d_blk%d_size' % (d, i, n)] = s
284+
for d, s in zip(['x', 'y', 'z'], level, strict=True):
285+
options[f'{d}{i}_blk{n}_size'] = s
277286

278287
solver = setup(space_order=space_order, time_order=time_order, **kwargs)
279288
if warmup:
@@ -345,7 +354,7 @@ def run_jit_backdoor(problem, **kwargs):
345354

346355
if not os.path.exists(cfile):
347356
# First time we run this problem, let's generate and jit-compile code
348-
op.cfunction
357+
_ = op.cfunction
349358
info(f"You may now edit the generated code in `{cfile}`. "
350359
"Then save the file, and re-run this benchmark.")
351360
return
@@ -403,9 +412,10 @@ def test(problem, **kwargs):
403412
set_log_level('DEBUG', comm=MPI.COMM_WORLD)
404413

405414
if MPI.COMM_WORLD.size > 1 and not configuration['mpi']:
406-
warning("It seems that you're running over MPI with %d processes, but "
407-
"DEVITO_MPI is unset. Setting `DEVITO_MPI=basic`..."
408-
% MPI.COMM_WORLD.size)
415+
warning(
416+
f'It seems that you are running over MPI with {MPI.COMM_WORLD.size} '
417+
'processes, but DEVITO_MPI is unset. Setting `DEVITO_MPI=basic`...'
418+
)
409419
configuration['mpi'] = 'basic'
410420
except (TypeError, ModuleNotFoundError):
411421
# MPI not available
@@ -417,8 +427,6 @@ def test(problem, **kwargs):
417427

418428
benchmark(standalone_mode=False)
419429

420-
try:
430+
# In case MPI not available
431+
with suppress(TypeError):
421432
MPI.Finalize()
422-
except TypeError:
423-
# MPI not available
424-
pass

conftest.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import sys
3+
from contextlib import suppress
34
from subprocess import check_call
45

56
import pytest
@@ -51,17 +52,18 @@ def skipif(items, whole_module=False):
5152
langs = configuration._accepted['language']
5253
if any(i == f'device-{l}' and configuration['language'] == l for l in langs)\
5354
and isinstance(configuration['platform'], Device):
54-
skipit = "language `{}` for device unsupported".format(configuration['language'])
55+
skipit = f'language `{configuration["language"]}` for device unsupported'
5556
break
5657
if any(i == f'device-{k}' and isinstance(configuration['compiler'], v)
5758
for k, v in compiler_registry.items()) and\
5859
isinstance(configuration['platform'], Device):
59-
skipit = "compiler `{}` for device unsupported".format(configuration['compiler'])
60+
skipit = f'compiler `{configuration["compiler"]}` for device unsupported'
6061
break
6162
# Skip if must run on GPUs but not currently on a GPU
6263
if i in ('nodevice', 'nodevice-omp', 'nodevice-acc') and\
6364
not isinstance(configuration['platform'], Device):
64-
skipit = ("must run on device, but currently on `{}`".format(configuration['platform'].name))
65+
skipit = 'must run on device, but currently on '
66+
skipit += f'`{configuration["platform"].name}`'
6567
break
6668
# Skip if it won't run with nvc on CPU backend
6769
if i == 'cpu64-nvc' and \
@@ -193,7 +195,7 @@ def parallel(item, m):
193195
]
194196
if nprocs > 1:
195197
args.extend([
196-
":", "-n", "%d" % (nprocs - 1), pyversion, "-m", "pytest",
198+
":", "-n", str(nprocs - 1), pyversion, "-m", "pytest",
197199
"-s", "--runxfail", "-v", "--timeout=600", "--timeout-method=thread",
198200
"-o faulthandler_timeout=660", testname
199201
])
@@ -253,10 +255,8 @@ def pytest_generate_tests(metafunc):
253255
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
254256
def pytest_runtest_call(item):
255257
inside_pytest_marker = os.environ.get('DEVITO_PYTEST_FLAG', 0)
256-
try:
258+
with suppress(ValueError):
257259
inside_pytest_marker = int(inside_pytest_marker)
258-
except ValueError:
259-
pass
260260

261261
if inside_pytest_marker:
262262
outcome = yield
@@ -287,15 +287,13 @@ def pytest_runtest_makereport(item, call):
287287
result = outcome.get_result()
288288

289289
inside_pytest_marker = os.environ.get('DEVITO_PYTEST_FLAG', 0)
290-
try:
290+
with suppress(ValueError):
291291
inside_pytest_marker = int(inside_pytest_marker)
292-
except ValueError:
293-
pass
294292
if inside_pytest_marker:
295293
return
296294

297295
if item.get_closest_marker("parallel") or \
298-
item.get_closest_marker("decoupler"):
296+
item.get_closest_marker("decoupler"): # noqa: SIM102
299297
if call.when == 'call' and result.outcome == 'skipped':
300298
result.outcome = 'passed'
301299

0 commit comments

Comments
 (0)