Skip to content

Commit

Permalink
Merge pull request #64 from elbeejay/runtime
Browse files Browse the repository at this point in the history
Utility Function: Model runtime from the log-file
  • Loading branch information
elbeejay authored Aug 20, 2021
2 parents 9493e0f + c1f5160 commit 8327891
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
29 changes: 29 additions & 0 deletions deltametrics/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import numpy as np
import xarray as xr
from scipy import optimize
import time
import datetime

from numba import njit

Expand Down Expand Up @@ -538,3 +540,30 @@ def _points_in_polygon(points, polygon):
inside[i] = _point_in_polygon(points[i, 0], points[i, 1], polygon)

return inside


def runtime_from_log(logname):
"""Calculate the model runtime from the logfile.
Uses the timestamps in the logfile to compute the model runtime.
Parameters
----------
logname : :obj:`str:`
Path to the model logfile that you wish to get the runtime for
Returns
-------
runtime : :obj:`float`
Float of the model runtime in seconds.
"""
with open(logname) as f:
lines = f.readlines()
start = lines[0][:19]
t_start = time.strptime(start, '%Y-%m-%d %H:%M:%S')
t1 = time.mktime(t_start)
fin = lines[-1][:19]
t_end = time.strptime(fin, '%Y-%m-%d %H:%M:%S')
t2 = time.mktime(t_end)
te = datetime.timedelta(seconds=t2-t1)
return te.total_seconds()
17 changes: 16 additions & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import pytest

import os
import numpy as np

from deltametrics import utils
Expand Down Expand Up @@ -129,7 +130,7 @@ def test_exponential_fit():
assert pytest.approx(yfit == np.array([10.02900253, 4.85696353,
2.22612537, 0.88790858]))
assert pytest.approx(popts == np.array([10.02900253, -0.49751195,
0.67596451]))
0.67596451]))
assert pytest.approx(cov == np.array([[0.0841566, 0.04554967, 0.01139969],
[0.04554967, 0.59895713, 0.08422946],
[0.01139969, 0.08422946,
Expand Down Expand Up @@ -203,3 +204,17 @@ def test_format_table_float():
_val = int(5.2)
_fnum = utils.format_table(_val)
assert _fnum == '5'


@pytest.mark.xfail(raises=ImportError,
reason='pyDeltaRCM is not a required dependency')
def test_time_from_log(tmp_path):
"""Generate run+logfile and then read runtime from it."""
from pyDeltaRCM.model import DeltaModel
delta = DeltaModel(out_dir=str(tmp_path)) # init delta to make log file
delta.finalize() # finalize and end log file
log_path = os.path.join(tmp_path, os.listdir(tmp_path)[0]) # path to log
elapsed_time = utils.runtime_from_log(log_path)
# elapsed time should exceed 0, but exact time will vary
assert isinstance(elapsed_time, float)
assert elapsed_time > 0

0 comments on commit 8327891

Please sign in to comment.