---
title: Timer
description: >-
  The Timer callback tracks the time spent in the training, validation, and test
  loops and interrupts the Trainer

  if the given time limit for the training loop is reached.
canonical: >-
  https://lightning.ai/docs/pytorch/stable/optional-api/api/lightning.pytorch.callbacks.Timer
---
# Timer {#timer}

### `class lightning.pytorch.callbacks.Timer(duration=None, interval=Interval.step, verbose=True)` {#lightning.pytorch.callbacks.Timer}

Bases: [`Callback`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.Callback.md#lightning.pytorch.callbacks.Callback "lightning.pytorch.callbacks.callback.Callback")

The Timer callback tracks the time spent in the training, validation, and test loops and interrupts the Trainer if the given time limit for the training loop is reached.

Parameters:

*   **duration** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.15)"), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – A string in the format DD:HH:MM:SS (days, hours, minutes seconds), or a [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.15)"), or a dict containing key-value compatible with [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.15)").
    
*   **interval** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – Determines if the interruption happens on epoch level or mid-epoch. Can be either `"epoch"` or `"step"`.
    
*   **verbose** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Set this to `False` to suppress logging messages.
    

Raises:

*   **MisconfigurationException** – If `duration` is not in the expected format.
    
*   **MisconfigurationException** – If `interval` is not one of the supported choices.
    

Example:

```python
from lightning.pytorch import Trainer
from lightning.pytorch.callbacks import Timer

# stop training after 12 hours
timer = Timer(duration="00:12:00:00")

# or provide a datetime.timedelta
from datetime import timedelta
timer = Timer(duration=timedelta(weeks=1))

# or provide a dictionary
timer = Timer(duration=dict(weeks=4, days=2))

# force training to stop after given time limit
trainer = Trainer(callbacks=[timer])

# query training/validation/test time (in seconds)
timer.time_elapsed("train")
timer.start_time("validate")
timer.end_time("test")
```

#### `end_time(stage=RunningStage.TRAINING)` {#lightning.pytorch.callbacks.Timer.end_time}

Return the end time of a particular stage (in seconds)

Return type:

[`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]

#### `load_state_dict(state_dict)` {#lightning.pytorch.callbacks.Timer.load_state_dict}

Called when loading a checkpoint, implement to reload callback state given callback’s `state_dict`.

Parameters:

**state\_dict** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – the callback state returned by `state_dict`.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `on_fit_start(trainer, *args, **kwargs)` {#lightning.pytorch.callbacks.Timer.on_fit_start}

Called when fit begins.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `on_test_end(trainer, pl_module)` {#lightning.pytorch.callbacks.Timer.on_test_end}

Called when the test ends.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `on_test_start(trainer, pl_module)` {#lightning.pytorch.callbacks.Timer.on_test_start}

Called when the test begins.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `on_train_batch_end(trainer, *args, **kwargs)` {#lightning.pytorch.callbacks.Timer.on_train_batch_end}

Called when the train batch ends. :rtype: [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

Note

The value `outputs["loss"]` here will be the normalized value w.r.t `accumulate_grad_batches` of the loss returned from `training_step`.

#### `on_train_end(trainer, pl_module)` {#lightning.pytorch.callbacks.Timer.on_train_end}

Called when the train ends.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `on_train_epoch_end(trainer, *args, **kwargs)` {#lightning.pytorch.callbacks.Timer.on_train_epoch_end}

Called when the train epoch ends.

To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the [`lightning.pytorch.core.LightningModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule") and access them in this hook:

```python
class MyLightningModule(L.LightningModule):
    def __init__(self):
        super().__init__()
        self.training_step_outputs = []

    def training_step(self):
        loss = ...
        self.training_step_outputs.append(loss)
        return loss


class MyCallback(L.Callback):
    def on_train_epoch_end(self, trainer, pl_module):
        # do something with all training_step outputs, for example:
        epoch_mean = torch.stack(pl_module.training_step_outputs).mean()
        pl_module.log("training_epoch_mean", epoch_mean)
        # free up the memory
        pl_module.training_step_outputs.clear()
```

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `on_train_start(trainer, pl_module)` {#lightning.pytorch.callbacks.Timer.on_train_start}

Called when the train begins.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `on_validation_end(trainer, pl_module)` {#lightning.pytorch.callbacks.Timer.on_validation_end}

Called when the validation loop ends.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `on_validation_start(trainer, pl_module)` {#lightning.pytorch.callbacks.Timer.on_validation_start}

Called when the validation loop begins.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `start_time(stage=RunningStage.TRAINING)` {#lightning.pytorch.callbacks.Timer.start_time}

Return the start time of a particular stage (in seconds)

Return type:

[`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]

#### `state_dict()` {#lightning.pytorch.callbacks.Timer.state_dict}

Called when saving a checkpoint, implement to generate callback’s `state_dict`.

Return type:

[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]

Returns:

A dictionary containing callback state.

#### `time_elapsed(stage=RunningStage.TRAINING)` {#lightning.pytorch.callbacks.Timer.time_elapsed}

Return the time elapsed for a particular stage (in seconds)

Return type:

[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")

#### `time_remaining(stage=RunningStage.TRAINING)` {#lightning.pytorch.callbacks.Timer.time_remaining}

Return the time remaining for a particular stage (in seconds)

Return type:

[`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]

---

**Navigation**

- Parent: [Api](/docs/pytorch/2.6.6/optional-api/api.md)
