---
title: "Why pipetime?"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{why_pipetime}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
# Suppress vignette title mismatch warning
options(rmarkdown.html_vignette.check_title = FALSE)
```

```{r setup, message=FALSE, warning=FALSE}
library(pipetime)
library(dplyr)
```

R pipelines (`|>`) allow chaining operations in a readable, sequential way. Existing timing tools (e.g. `system.time()`, `tictoc`) do not integrate naturally with pipelines and tidy workflows. `pipetime` solves this by letting you measure time inline, without interrupting the pipeline.

# Examples
```{r}
slow_op <- function(x) {
  Sys.sleep(0.1)  # Simulate a time-consuming operation
  x^2
}
```

## `system.time()`

```{r, error=TRUE}
# Must wrap the entire pipeline, breaking the flow
the_time <- system.time({
  df <- data.frame(x = 1:3) |>
    mutate(y = slow_op(x)) |>
    summarise(mean_y = mean(y))
})
the_time
df

# system.time() cannot be inserted inline in a pipeline:
data.frame(x = 1:3) |>
  mutate(y = slow_op(x)) |>
  # system.time() would break the pipeline here
  summarise(mean_y = mean(y))
```

## `tictoc`

```{r}
library(tictoc)

# Requires manual start/stop
tic("total pipeline")
df <- data.frame(x = 1:3) |>
  mutate(y = slow_op(x)) |>
  summarise(mean_y = mean(y))
toc()
df
```

## `time_pipe`

```{r}
# Inline timing checkpoints, pipeline stays intact
data.frame(x = 1:3) |>
  mutate(y = slow_op(x)) |>
  time_pipe("after mutate") |>
  summarise(mean_y = mean(y)) |>
  time_pipe("total pipeline")

```

# Why `pipetime`?

-   Works directly inside pipelines.

-   Supports multiple checkpoints.

-   Prints or logs timings in `.pipetime_env` (see `?get_log`).