vfdev-5: @erip I think we should keep previous behavious about logging h,m,s times.

About the tests, I think we can just check the presence of values.
erip: You want to log the h,m,s times in the engine, but store the timestamp?
vfdev-5: > You want to log the h,m,s times in the engine, but store the timestamp?

Yes, I want to keep previous engine's behaviour and in addition to store the timestamp.
vfdev-5: Looking into this code now:
```python
                time_taken = self._run_once_on_dataset()
                self.state.times[Events.EPOCH_COMPLETED.name] = time_taken
                hours, mins, secs = _to_hours_mins_secs(time_taken)
                self.logger.info("Epoch[%s] Complete. Time taken: %02d:%02d:%02d", self.state.epoch, hours, mins, secs)
                if self.should_terminate:
                    break
                self._fire_event(Events.EPOCH_COMPLETED)
```
In case if `should_terminate` is True, we log and set the time of a completed epoch, but we do not trigger the event... I need to think if this is OK or we need to trigger the event...
vfdev-5: > Excellent. This initialization happens in the State constructor, but I forgot to remove this from the test; that said, I think that's slightly different than wiring up the event handler.

> Is there some place where it makes sense to wire this or is engine.run good enough?

Good point, we need to check what happens if we run multiple times evaluator and whether times are still correct. Do we need to include that into state dict (maybe not) ?

vfdev-5: And @erip I think it is déjàvu, are these values good for a single process and for DDP multi-process ?
erip: >we need to check what happens if we run multiple times 

Ok, I'll add another test. :)

> Do we need to include that into state dict?

Currently no. It's unclear if these would be useful in the state info. If they were, I imagine it would just be simple enough to (de)serialize the values.
vfdev-5: @erip thanks for the updates! Could you please update the docstring of `Engine` and show the usage in `examples/mnist/mnist.py`.
erip: Absolutely
erip: @vfdev-5 thanks for catching the missed TODO comments. Please let me know if there's anything else you want me to polish
vfdev-5: @erip I thinks we are good with this one. Could you, please, take a look at this issue : https://github.com/pytorch/ignite/issues/784
 with `Frequency` you worked previously ? 
erip: Are the tests normally this flaky? The failure seems unrelated, but I've seen the same test fail a few times.
vfdev-5: @erip OK, I understand now why tests are failing. In FastaiLRFiner tests we check that there is no more attached handlers, by default `Engine` has no internally attached handlers
```
    def test_with_attach(lr_finder, to_save, dummy_engine, dataloader):

        with lr_finder.attach(dummy_engine, to_save=to_save) as trainer_with_finder:
            trainer_with_finder.run(dataloader)

        assert lr_finder.get_results() is not None
        for event in dummy_engine._event_handlers:
>           assert len(dummy_engine._event_handlers[event]) == 0
```
and here we added `_init_timers` on started. Maybe we can call this method inside `run` and keep previous behaviour.
diff --git a/examples/mnist/mnist.py b/examples/mnist/mnist.py
index 4a23028d..93886113 100644
--- a/examples/mnist/mnist.py
+++ b/examples/mnist/mnist.py
@@ -99,6 +99,12 @@ def run(train_batch_size, val_batch_size, epochs, lr, momentum, log_interval):
 
         pbar.n = pbar.last_print_n = 0
 
+    @trainer.on(Events.EPOCH_COMPLETED | Events.COMPLETED)
+    def log_time(engine):
+        tqdm.write(
+            "{} took {} seconds".format(trainer.last_event_name.name, trainer.state.times[trainer.last_event_name.name])
+        )
+
     trainer.run(train_loader, max_epochs=epochs)
     pbar.close()
 
diff --git a/ignite/engine/engine.py b/ignite/engine/engine.py
index b8a457f9..b6decfeb 100644
--- a/ignite/engine/engine.py
+++ b/ignite/engine/engine.py
@@ -433,7 +433,7 @@ class Engine:
         )
         self.should_terminate_single_epoch = True
 
-    def _run_once_on_dataset(self) -> Tuple[int, int, int]:
+    def _run_once_on_dataset(self) -> float:
         start_time = time.time()
 
         # We need to setup iter_counter > 0 if we resume from an iteration
@@ -497,10 +497,7 @@ class Engine:
             self.logger.error("Current run is terminating due to exception: %s.", str(e))
             self._handle_exception(e)
 
-        time_taken = time.time() - start_time
-        hours, mins, secs = _to_hours_mins_secs(time_taken)
-
-        return hours, mins, secs
+        return time.time() - start_time
 
     def _handle_exception(self, e: Exception) -> None:
         if Events.EXCEPTION_RAISED in self._event_handlers:
@@ -619,7 +616,8 @@ class Engine:
 
         Engine has a state and the following logic is applied in this function:
 
-        - At the first call, new state is defined by `max_epochs`, `epoch_length`, `seed` if provided.
+        - At the first call, new state is defined by `max_epochs`, `epoch_length`, `seed` if provided. A timer for
+            total and per-epoch time is initialized when Events.STARTED is handled.
         - If state is already defined such that there are iterations to run until `max_epochs` and no input arguments
             provided, state is kept and used in the function.
         - If state is defined and engine is "done" (no iterations to run until `max_epochs`), a new state is defined.
@@ -690,6 +688,11 @@ class Engine:
         self.state.dataloader = data
         return self._internal_run()
 
+    @staticmethod
+    def _init_timers(state: State):
+        state.times[Events.EPOCH_COMPLETED.name] = 0.0
+        state.times[Events.COMPLETED.name] = 0.0
+
     def _setup_engine(self) -> None:
 
         try:
@@ -775,6 +778,7 @@ class Engine:
 
     def _internal_run(self) -> State:
         self.should_terminate = self.should_terminate_single_epoch = False
+        self._init_timers(self.state)
         try:
             start_time = time.time()
             self._fire_event(Events.STARTED)
@@ -785,16 +789,18 @@ class Engine:
                 if self._dataloader_iter is None:
                     self._setup_engine()
 
-                hours, mins, secs = self._run_once_on_dataset()
-
+                time_taken = self._run_once_on_dataset()
+                self.state.times[Events.EPOCH_COMPLETED.name] = time_taken
+                hours, mins, secs = _to_hours_mins_secs(time_taken)
                 self.logger.info("Epoch[%s] Complete. Time taken: %02d:%02d:%02d", self.state.epoch, hours, mins, secs)
                 if self.should_terminate:
                     break
                 self._fire_event(Events.EPOCH_COMPLETED)
 
-            self._fire_event(Events.COMPLETED)
             time_taken = time.time() - start_time
             hours, mins, secs = _to_hours_mins_secs(time_taken)
+            self.state.times[Events.COMPLETED.name] = time_taken
+            self._fire_event(Events.COMPLETED)
             self.logger.info("Engine run complete. Time taken %02d:%02d:%02d" % (hours, mins, secs))
 
         except BaseException as e:
diff --git a/ignite/engine/events.py b/ignite/engine/events.py
index 7ebab19c..1e3de579 100644
--- a/ignite/engine/events.py
+++ b/ignite/engine/events.py
@@ -246,6 +246,8 @@ class State:
         state.batch             # batch passed to `process_function`
         state.output            # output of `process_function` after a single iteration
         state.metrics           # dictionary with defined metrics if any
+        state.times             # dictionary with total and per-epoch times fetched on
+                                # keys: Events.EPOCH_COMPLETED.name and Events.COMPLETED.name
 
     """
 
@@ -270,6 +272,7 @@ class State:
         self.metrics = {}
         self.dataloader = None
         self.seed = None
+        self.times = {Events.EPOCH_COMPLETED.name: None, Events.COMPLETED.name: None}
 
         for k, v in kwargs.items():
             setattr(self, k, v)

Insert logged times into state
## 🚀 Feature

By default, Engine measures times for single epoch and total run. These times are logged with `engine.logger`:
https://github.com/pytorch/ignite/blob/efc45a79ee0a5bf8105c3caff194758439db2426/ignite/engine/engine.py#L793-L796
and
https://github.com/pytorch/ignite/blob/efc45a79ee0a5bf8105c3caff194758439db2426/ignite/engine/engine.py#L497-L500

 Idea is to put these times (at least `time_taken` for epoch and total time) into `engine.state` under a name (e.g. "times"). Such that we can also use this information without need to use `Timer` or setup logger.
diff --git a/tests/ignite/engine/test_engine.py b/tests/ignite/engine/test_engine.py
index bd66f6dc..1d49728c 100644
--- a/tests/ignite/engine/test_engine.py
+++ b/tests/ignite/engine/test_engine.py
@@ -1,4 +1,5 @@
 import os
+import time
 import pytest
 from unittest.mock import call, MagicMock, Mock
 
@@ -366,6 +367,27 @@ def test_state_get_event_attrib_value():
     assert state.get_event_attrib_value(e) == state.epoch
 
 
+def test_time_stored_in_state():
+    def _test(data, max_epochs, epoch_length):
+        sleep_time = 0.01
+        engine = Engine(lambda e, b: time.sleep(sleep_time))
+
+        def check_epoch_time(engine):
+            assert engine.state.times[Events.EPOCH_COMPLETED.name] >= sleep_time * epoch_length
+
+        def check_completed_time(engine):
+            assert engine.state.times[Events.COMPLETED.name] >= sleep_time * epoch_length * max_epochs
+
+        engine.add_event_handler(Events.EPOCH_COMPLETED, lambda e: check_epoch_time(e))
+        engine.add_event_handler(Events.COMPLETED, lambda e: check_completed_time(e))
+
+        engine.run(data, max_epochs=max_epochs, epoch_length=epoch_length)
+
+    _test(list(range(100)), max_epochs=2, epoch_length=100)
+    _test(list(range(200)), max_epochs=2, epoch_length=100)
+    _test(list(range(200)), max_epochs=5, epoch_length=100)
+
+
 def _test_run_check_triggered_events():
     def _test(data, max_epochs, epoch_length):
         engine = Engine(lambda e, b: 1)

pip install -e .
parse_log_pytest
requirements.txt
pytest
apt-get update apt-get install -y gcc pip install torch torchvision -f https://download.pytorch.org/whl/cpu/torch_stable.html -U
3.7
requirements-dev.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
absl-py==2.1.0
alembic==1.12.1
arrow==1.2.3
attrs==24.2.0
boto3==1.33.13
botocore==1.33.13
bravado==11.1.0
bravado-core==6.1.1
cached-property==1.5.2
cachetools==5.5.2
certifi @ file:///croot/certifi_1671487769961/work/certifi
charset-normalizer==3.4.1
click==7.1.2
cloudpickle==2.2.1
codecov==2.1.13
coverage==7.2.7
cycler==0.11.0
databricks-cli==0.18.0
dill==0.3.7
docker==6.1.3
entrypoints==0.4
exceptiongroup==1.2.2
execnet==2.0.2
Flask==1.1.4
fonttools==4.38.0
fqdn==1.5.1
future==1.0.0
gitdb==4.0.12
GitPython==3.1.44
google-auth==2.38.0
google-auth-oauthlib==0.4.6
greenlet==3.1.1
grpcio==1.62.3
gunicorn==20.1.0
gym==0.26.2
gym-notices==0.0.8
hestia==0.6.0
idna==3.10
importlib-metadata==5.2.0
importlib-resources==5.12.0
iniconfig==2.0.0
isoduration==20.11.0
itsdangerous==1.1.0
Jinja2==2.10.3
jmespath==1.0.1
joblib==1.3.2
jsonpatch==1.33
jsonpointer==3.0.0
jsonref==1.1.0
jsonschema==4.17.3
kiwisolver==1.4.5
Mako==1.2.4
Markdown==3.4.4
MarkupSafe==2.1.5
marshmallow==3.0.0rc5
matplotlib==3.5.3
mlflow==1.30.1
monotonic==1.6
msgpack==1.0.5
neptune-client==1.11.1
networkx==2.6.3
numpy==1.21.6
oauthlib==3.2.2
packaging==21.3
pandas==1.3.5
Pillow==9.5.0
pkgutil_resolve_name==1.3.10
pluggy==1.2.0
polyaxon-client==0.6.1
polyaxon-schemas==0.6.1
polystores==0.2.5
prometheus-client==0.17.1
prometheus_flask_exporter==0.23.2
protobuf==3.20.3
psutil==7.0.0
pyasn1==0.5.1
pyasn1-modules==0.3.0
PyJWT==2.8.0
pynvml==11.5.3
pyparsing==3.1.4
pyrsistent==0.19.3
pytest==7.4.4
pytest-cov==4.1.0
pytest-xdist==3.5.0
python-dateutil==2.9.0.post0
-e git+https://github.com/pytorch/ignite.git@68fa8a86b34786f541a259c1089107cb07a9b3a1#egg=pytorch_ignite
pytz==2022.7.1
PyYAML==6.0.1
querystring-parser==1.2.4
requests==2.31.0
requests-oauthlib==2.0.0
requests-toolbelt==1.0.0
rfc3339-validator==0.1.4
rfc3986-validator==0.1.1
rhea==0.5.5
rsa==4.9
s3transfer==0.8.2
scikit-learn==1.0.2
scipy==1.7.3
simplejson==3.20.1
six==1.17.0
smmap==5.0.2
SQLAlchemy==1.4.54
sqlparse==0.4.4
swagger-spec-validator==3.0.3
tabulate==0.9.0
tensorboard==2.11.2
tensorboard-data-server==0.6.1
tensorboard-plugin-wit==1.8.1
tensorboardX==2.6.2.2
threadpoolctl==3.1.0
tomli==2.0.1
torch==1.13.1+cpu
torchvision==0.14.1+cpu
tornado==6.2
tqdm==4.67.1
typing_extensions==4.7.1
uri-template==1.3.0
urllib3==1.26.20
visdom==0.2.4
webcolors==1.13
websocket-client==1.6.1
Werkzeug==1.0.1
zipp==3.15.0

name: ignite
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2022.12.7=py37h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.4.4=h6a678d5_1
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - pip=22.3.1=py37h06a4308_0
  - python=3.7.16=h7a1cb2a_0
  - readline=8.2=h5eee18b_0
  - setuptools=65.6.3=py37h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - wheel=0.38.4=py37h06a4308_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - absl-py==2.1.0
      - alembic==1.12.1
      - arrow==1.2.3
      - attrs==24.2.0
      - boto3==1.33.13
      - botocore==1.33.13
      - bravado==11.1.0
      - bravado-core==6.1.1
      - cached-property==1.5.2
      - cachetools==5.5.2
      - charset-normalizer==3.4.1
      - click==7.1.2
      - cloudpickle==2.2.1
      - codecov==2.1.13
      - coverage==7.2.7
      - cycler==0.11.0
      - databricks-cli==0.18.0
      - dill==0.3.7
      - docker==6.1.3
      - entrypoints==0.4
      - exceptiongroup==1.2.2
      - execnet==2.0.2
      - flask==1.1.4
      - fonttools==4.38.0
      - fqdn==1.5.1
      - future==1.0.0
      - gitdb==4.0.12
      - gitpython==3.1.44
      - google-auth==2.38.0
      - google-auth-oauthlib==0.4.6
      - greenlet==3.1.1
      - grpcio==1.62.3
      - gunicorn==20.1.0
      - gym==0.26.2
      - gym-notices==0.0.8
      - hestia==0.6.0
      - idna==3.10
      - importlib-metadata==5.2.0
      - importlib-resources==5.12.0
      - iniconfig==2.0.0
      - isoduration==20.11.0
      - itsdangerous==1.1.0
      - jinja2==2.10.3
      - jmespath==1.0.1
      - joblib==1.3.2
      - jsonpatch==1.33
      - jsonpointer==3.0.0
      - jsonref==1.1.0
      - jsonschema==4.17.3
      - kiwisolver==1.4.5
      - mako==1.2.4
      - markdown==3.4.4
      - markupsafe==2.1.5
      - marshmallow==3.0.0rc5
      - matplotlib==3.5.3
      - mlflow==1.30.1
      - monotonic==1.6
      - msgpack==1.0.5
      - neptune-client==1.11.1
      - networkx==2.6.3
      - numpy==1.21.6
      - oauthlib==3.2.2
      - packaging==21.3
      - pandas==1.3.5
      - pillow==9.5.0
      - pkgutil-resolve-name==1.3.10
      - pluggy==1.2.0
      - polyaxon-client==0.6.1
      - polyaxon-schemas==0.6.1
      - polystores==0.2.5
      - prometheus-client==0.17.1
      - prometheus-flask-exporter==0.23.2
      - protobuf==3.20.3
      - psutil==7.0.0
      - pyasn1==0.5.1
      - pyasn1-modules==0.3.0
      - pyjwt==2.8.0
      - pynvml==11.5.3
      - pyparsing==3.1.4
      - pyrsistent==0.19.3
      - pytest==7.4.4
      - pytest-cov==4.1.0
      - pytest-xdist==3.5.0
      - python-dateutil==2.9.0.post0
      - pytorch-ignite==0.4.0
      - pytz==2022.7.1
      - pyyaml==6.0.1
      - querystring-parser==1.2.4
      - requests==2.31.0
      - requests-oauthlib==2.0.0
      - requests-toolbelt==1.0.0
      - rfc3339-validator==0.1.4
      - rfc3986-validator==0.1.1
      - rhea==0.5.5
      - rsa==4.9
      - s3transfer==0.8.2
      - scikit-learn==1.0.2
      - scipy==1.7.3
      - simplejson==3.20.1
      - six==1.17.0
      - smmap==5.0.2
      - sqlalchemy==1.4.54
      - sqlparse==0.4.4
      - swagger-spec-validator==3.0.3
      - tabulate==0.9.0
      - tensorboard==2.11.2
      - tensorboard-data-server==0.6.1
      - tensorboard-plugin-wit==1.8.1
      - tensorboardx==2.6.2.2
      - threadpoolctl==3.1.0
      - tomli==2.0.1
      - torch==1.13.1+cpu
      - torchvision==0.14.1+cpu
      - tornado==6.2
      - tqdm==4.67.1
      - typing-extensions==4.7.1
      - uri-template==1.3.0
      - urllib3==1.26.20
      - visdom==0.2.4
      - webcolors==1.13
      - websocket-client==1.6.1
      - werkzeug==1.0.1
      - zipp==3.15.0
prefix: /opt/conda/envs/ignite

tests/ignite/engine/test_engine.py::test_time_stored_in_state
tests/ignite/engine/test_engine.py::test_terminate tests/ignite/engine/test_engine.py::test_invalid_process_raises_with_invalid_signature tests/ignite/engine/test_engine.py::test_current_epoch_counter_increases_every_epoch tests/ignite/engine/test_engine.py::test_current_iteration_counter_increases_every_iteration tests/ignite/engine/test_engine.py::test_stopping_criterion_is_max_epochs tests/ignite/engine/test_engine.py::test_terminate_at_end_of_epoch_stops_run tests/ignite/engine/test_engine.py::test_terminate_at_start_of_epoch_stops_run_after_completing_iteration tests/ignite/engine/test_engine.py::test_terminate_stops_run_mid_epoch tests/ignite/engine/test_engine.py::test_terminate_epoch_stops_mid_epoch tests/ignite/engine/test_engine.py::test_iteration_events_are_fired tests/ignite/engine/test_engine.py::test_last_event_name tests/ignite/engine/test_engine.py::test_reset_should_terminate tests/ignite/engine/test_engine.py::test_batch_values tests/ignite/engine/test_engine.py::test_state_repr tests/ignite/engine/test_engine.py::test_alter_batch tests/ignite/engine/test_engine.py::test__is_done tests/ignite/engine/test_engine.py::test__setup_engine tests/ignite/engine/test_engine.py::test_run_asserts tests/ignite/engine/test_engine.py::test_state_get_event_attrib_value tests/ignite/engine/test_engine.py::test_run_check_triggered_events tests/ignite/engine/test_engine.py::test_run_check_triggered_events_on_iterator tests/ignite/engine/test_engine.py::test_distrib_cpu tests/ignite/engine/test_engine.py::test_engine_with_iterable_dataloader tests/ignite/engine/test_engine.py::test_engine_random_state
ignite/engine/events.py ignite/engine/engine.py examples/mnist/mnist.py
ignite/engine/events.py ignite/engine/engine.py examples/mnist/mnist.py