Website Vidya
Cloud & DevOpsStep-by-Step Guide

time Command in Linux: Measure Execution Time and Resources

Learn time command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
11 min read
PDF Cheat Sheet
time Command in Linux: Measure Execution Time and Resources
AI Executive SummaryWebsiteVidya AI

11 min read

Learn time command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What time Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

The time command in linux is the primary benchmarking and resource profiling tool for developers, performance engineers, and system administrators. Whether you are optimizing a Python algorithm, comparing compression ratios across different archival tools, evaluating database query performance, or sizing container memory limits, measuring execution duration and hardware resource consumption is the first step in performance engineering.

A critical distinction every Linux practitioner must understand is that typing time in an interactive terminal usually invokes a shell keyword or builtin provided by Bash, Zsh, or Ksh—not the standalone binary. While the shell builtin provides quick, high-level summaries of elapsed wall-clock and CPU time, the standalone GNU binary located at /usr/bin/time unlocks deep kernel-level telemetry, including peak Resident Set Size (RSS), minor and major page faults, voluntary context switches, and filesystem block inputs/outputs.

By learning how to interpret real (wall-clock), user (user-space CPU), and sys (kernel-space CPU) time metrics and leveraging GNU time's verbose formatting options, you can accurately diagnose whether an application is CPU-bound, memory-starved, or stalled waiting on storage I/O.

Advertisement
time Command in Linux: Measure Execution Time and Resources — syntax, flags, and practical terminal workflow diagram
time Command in Linux: Measure Execution Time and Resources — command syntax, key options, and production workflow reference.

What time Does and When to Use It

At the Linux kernel level, timing and resource harvesting rely on the wait4(2) system call and the kernel's process accounting subsystems. When time (or /usr/bin/time) spawns the target program via fork(2) and execve(2), it records the initial system monotonic timestamp using clock_gettime(CLOCK_MONOTONIC). The parent process then blocks in wait4() until the child terminates.

Upon child termination, the Linux kernel populates a struct rusage structure (Resource Usage) containing precise telemetry captured during the child's lifespan. The kernel calculates: ru_utime (time spent executing instructions in user space), ru_stime (time spent executing kernel system calls on behalf of the process), ru_maxrss (the peak resident set size in kilobytes loaded into physical RAM), ru_minflt (minor page faults resolved without disk I/O), ru_majflt (major page faults requiring disk I/O), and context switches (voluntary when yielding for I/O vs involuntary when CPU time quantum expires).

Under the hood, time gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -v, -p, -o <file>, -a turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The time utility is packaged in time across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether time is installed and inspect which binary path and version your shell resolves:

type -a time
time --version 2>/dev/null || man -f time

# Illustrative output (reviewed against documentation)
time is /usr/bin/time
time (time)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y time

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y time

# Arch Linux
sudo pacman -S --noconfirm time

# Alpine Linux
sudo apk add --no-cache time

Command Syntax, Arguments, and Exit Status Codes

time [PIPELINE] | /usr/bin/time [OPTIONS] COMMAND [ARGS]

The syntax differs depending on which implementation is invoked: for the shell builtin, simply prepend time [PIPELINE] to measure a single command or an entire pipeline (e.g. time find / -name '*.log' | wc -l). To invoke the feature-rich GNU standalone utility, specify its absolute path or escape it: /usr/bin/time [OPTIONS] COMMAND [ARGS] or \time [OPTIONS] COMMAND [ARGS].

Key operational flags supported by the GNU /usr/bin/time binary include -v (or --verbose) to print a comprehensive multiline resource usage audit, -o <file> to redirect timing diagnostics to a file without contaminating standard application output, -a (or --append) to append results to an existing benchmark log, -f <format> to define custom formatted strings, and -p to enforce standard POSIX output format (real %e\nuser %U\nsys %S).

  • 0..255 — By standard design, time propagates the exact exit status of the timed child command.
  • 126 — The target command was located but could not be invoked (e.g. lacking execute permissions).
  • 127 — The target command was not found in the current system PATH.
  • 1..2 — Operational failure within the time utility itself (such as invalid format strings or file write errors).

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-v--verbosePrints exhaustive kernel resource telemetry including peak RSS, page faults, and context switches.
-p--portabilityEnforces the strict POSIX standard output format (real %e, user %U, sys %S).
-o <file>--output=<file>Redirects the resource telemetry output to a specified file rather than stderr.
-a--appendAppends timing output to the file specified with -o rather than overwriting it.
-f <fmt>--format=<fmt>Customizes output using format specifiers (%E elapsed, %M peak RAM, %P CPU percentage).
%EFormat specifierElapsed real wall-clock time in [hours:]minutes:seconds format.
%MFormat specifierMaximum resident set size (peak physical RAM consumed) in Kilobytes.
%PFormat specifierPercentage of total CPU allocated to the process during execution (e.g. 98%).
%FFormat specifierNumber of major (I/O-requiring) page faults incurred during execution.

Understanding the difference between real, user, and sys is essential for profiling. real is the actual wall-clock time elapsed from start to finish. user is CPU time spent in user-space code. sys is CPU time spent inside kernel system calls. If real is much greater than user + sys, the process was blocked waiting for external resources (disk I/O, network responses, or lock contention). If user + sys exceeds real, the process ran concurrently across multiple CPU cores.

Advertisement

While the built-in time is convenient for quick duration checks, only /usr/bin/time -v reveals memory footprint. For containerization and Kubernetes pod sizing, reading Maximum resident set size (kbytes) from /usr/bin/time -v provides the exact peak RAM metric needed to configure accurate container memory limits without risking Out-Of-Memory (OOM) kills.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Measure Command Duration with the Shell Builtin

Prepend the time keyword to any standard shell command to view elapsed real, user, and system CPU time.

time sleep 2

# Illustrative output (reviewed against documentation)
real    0m2.003s
user    0m0.001s
sys     0m0.002s

real shows 2.003 seconds elapsed, while user and sys are near zero because sleep yields CPU execution to the kernel.

2. Profile Complete Resource and Memory Footprint with /usr/bin/time -v

Invoke the standalone GNU time binary with -v to inspect peak RAM allocation, CPU percentage, and I/O counts.

/usr/bin/time -v gzip -c /var/log/syslog > /dev/null

# Illustrative output (reviewed against documentation)
Command being timed: "gzip -c /var/log/syslog"
        User time (seconds): 0.42
        System time (seconds): 0.04
        Percent of CPU this job got: 98%
        Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.47
        Average shared text size (kbytes): 0
        Average unshared data size (kbytes): 0
        Average stack size (kbytes): 0
        Average total size (kbytes): 0
        Maximum resident set size (kbytes): 2140
        Average resident set size (kbytes): 0
        Major (requiring I/O) page faults: 0
        Minor (reclaiming a frame) page faults: 312
        Voluntary context switches: 14
        Involuntary context switches: 4
        Swaps: 0
        File system inputs: 0
        File system outputs: 0
        Socket messages sent: 0
        Socket messages received: 0
        Signals delivered: 0
        Page size (bytes): 4096
        Exit status: 0

Maximum resident set size reveals gzip peaked at 2,140 KB (~2.1 MB) of RAM, and CPU percentage reached 98%.

3. Enforce Strict POSIX Formatting for Automated Parsing

Use the -p flag with /usr/bin/time to guarantee standardized POSIX output across diverse Unix environments.

/usr/bin/time -p tar -czf backup.tar.gz /etc 2>/dev/null

# Illustrative output (reviewed against documentation)
real 0.84
user 0.72
sys 0.11

POSIX format outputs exactly three lines with decimal seconds, making it trivial to parse with awk or cut in shell scripts.

4. Format Custom Benchmark Reports with Specifiers

Use the -f format option to output a single-line summary containing execution time, CPU percentage, and peak memory.

/usr/bin/time -f "Benchmark: %E real | %P CPU | %M KB peak RAM" python3 -c "[x**2 for x in range(1000000)]"

# Illustrative output (reviewed against documentation)
Benchmark: 0:00.12 real | 96% CPU | 39820 KB peak RAM

%E prints elapsed time (0:00.12), %P prints CPU utilization (96%), and %M prints peak memory consumption (~39.8 MB).

5. Save Benchmark Results to an Output File Without Polluting stderr

Redirect timing diagnostics directly to a file using -o and -a without mixing timing data into application output.

/usr/bin/time -o benchmark.log -a -f "%C: %E real, %M KB RAM" make build
cat benchmark.log

# Illustrative output (reviewed against documentation)
make build: 0:14.28 real, 184200 KB RAM

The -o flag writes timing statistics directly to benchmark.log, appending to historical test logs when paired with -a.

6. Measure Parallelism and Multi-Core Scaling

Time a multi-threaded build or compilation to verify whether jobs effectively utilize multiple CPU cores.

time make -j4

# Illustrative output (reviewed against documentation)
real    0m12.450s
user    0m42.120s
sys     0m03.210s

user (42.12s) + sys (3.21s) = 45.33s total CPU work completed in only 12.45s of real wall-clock time, proving multi-core parallel scaling.

Real-World Workflows, Pipelines, and Shell Automation

Benchmarking Compression Algorithms and Peak RAM Allocation in CI/CD

Run a quantitative benchmark comparing gzip, bzip2, and zstd to balance compression speed against memory and storage efficiency.

#!/usr/bin/env bash
set -euo pipefail

TEST_FILE="/tmp/sample_data.bin"
[ -f "${TEST_FILE}" ] || dd if=/dev/urandom of="${TEST_FILE}" bs=1M count=50 status=none

echo "=== Benchmarking Compression Utilities ==="
COMPRESSORS=("gzip -c" "bzip2 -c" "zstd -c -3")

for CMD in "${COMPRESSORS[@]}"; do
  TOOL=$(echo "${CMD}" | awk '{print $1}')
  echo "--------------------------------------------------"
  echo "Testing: ${TOOL}"
  /usr/bin/time -f "Elapsed Time: %E\nCPU Allocation: %P\nPeak RAM: %M KB\nExit Status: %x" \
    ${CMD} "${TEST_FILE}" > /dev/null
done

# Illustrative output (reviewed against documentation)
=== Benchmarking Compression Utilities ===
--------------------------------------------------
Testing: gzip
Elapsed Time: 0:01.42
CPU Allocation: 99%
Peak RAM: 2180 KB
Exit Status: 0
--------------------------------------------------
Testing: bzip2
Elapsed Time: 0:04.18
CPU Allocation: 99%
Peak RAM: 7820 KB
Exit Status: 0
--------------------------------------------------
Testing: zstd
Elapsed Time: 0:00.28
CPU Allocation: 98%
Peak RAM: 14200 KB
Exit Status: 0

Automating /usr/bin/time across compression tools provides the quantitative trade-off data (zstd is 5x faster but consumes more peak RAM).

Profiling Disk I/O vs CPU Bottlenecks on Slow Database Queries or Batch Scripts

Analyze an unoptimized batch process using system metrics to determine whether the bottleneck is storage I/O latency or raw CPU limits.

#!/usr/bin/env bash
set -euo pipefail

LOG="/tmp/batch_profile.txt"

echo "Profiling batch script execution..."
/usr/bin/time -v -o "${LOG}" python3 process_records.py

REAL_TIME=$(grep 'Elapsed' "${LOG}" | awk '{print $NF}')
USER_TIME=$(grep 'User time' "${LOG}" | awk '{print $NF}')
SYS_TIME=$(grep 'System time' "${LOG}" | awk '{print $NF}')
MAJOR_FAULTS=$(grep 'Major' "${LOG}" | awk '{print $NF}')
VOLUNTARY_CS=$(grep 'Voluntary context' "${LOG}" | awk '{print $NF}')

echo "Execution Summary:"
echo "- Wall Clock Time: ${REAL_TIME}"
echo "- CPU Time (User + Sys): $(awk "BEGIN {print ${USER_TIME} + ${SYS_TIME}}")s"
echo "- Major Page Faults (Disk Reads): ${MAJOR_FAULTS}"
echo "- Voluntary Context Switches: ${VOLUNTARY_CS}"

if [ "${MAJOR_FAULTS}" -gt 100 ] || [ "${VOLUNTARY_CS}" -gt 1000 ]; then
  echo "[DIAGNOSIS] Process is I/O-BOUND. High disk faulting or context switching detected."
else
  echo "[DIAGNOSIS] Process is CPU-BOUND. Optimizing code algorithms recommended."
fi

# Illustrative output (reviewed against documentation)
Profiling batch script execution...
Execution Summary:
- Wall Clock Time: 0:18.40
- CPU Time (User + Sys): 2.15s
- Major Page Faults (Disk Reads): 412
- Voluntary Context Switches: 3840
[DIAGNOSIS] Process is I/O-BOUND. High disk faulting or context switching detected.

Comparing wall-clock time (18.4s) against CPU time (2.15s) immediately proves the batch script was stalled waiting for disk reads.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding time inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Running time or /usr/bin/time does not require administrative or root privileges; process accounting via getrusage(2) is available to all unprivileged user processes for their own children. However, timing commands that perform cryptographic computations requires caution: high-resolution execution timing can expose side-channel timing attack vectors if cryptographic operations are not constant-time.

When timing commands that require elevated permissions via sudo, order matters: time sudo COMMAND times the entire sudo authentication and command lifecycle, whereas sudo /usr/bin/time COMMAND executes the timing binary as root and profiles only the target program.

GNU/Linux, BSD, and BusyBox Implementation Differences

The time command behaves differently across shells: Bash provides a keyword that supports timing shell pipelines (e.g. time foo | bar); Zsh provides a builtin with customized output formatting controlled by $TIMEFMT; and standard POSIX /bin/sh may not support time as a builtin.

The standalone binary /usr/bin/time is packaged in GNU time on Linux, whereas FreeBSD, OpenBSD, and macOS provide BSD versions of /usr/bin/time. The BSD implementation uses -l instead of -v to output resource usage and prints peak RSS in bytes rather than kilobytes.

Troubleshooting Common Errors and Diagnostics

time: -v: command not found or invalid option

Root Cause: Typing time invokes the shell builtin (e.g. in Bash), which does not support GNU options like -v, -o, or -f.

Resolution: Use the absolute path /usr/bin/time or escape the command with \time.

# Wrong: time -v ls
# Correct:
/usr/bin/time -v ls
# Or:
\time -v ls

Redirecting time output with 2> file.txt redirects the command's stderr instead

Root Cause: The shell builtin executes before redirections; attempting to redirect time redirects the child process streams.

Resolution: Group the command in a subshell or block: { time COMMAND; } 2> file.txt, or use /usr/bin/time -o file.txt.

{ time ls -la; } 2> timing_output.txt
# Or with GNU time:
/usr/bin/time -o timing_output.txt ls -la

Maximum resident set size reports 0 on certain platforms

Root Cause: Older Linux kernels or certain microkernel architectures did not reliably track ru_maxrss in rusage structures.

Resolution: Ensure you are running Linux kernel 2.6.32 or newer where rusage page tracking is fully implemented.

uname -r
/usr/bin/time -v true

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Real time is the actual wall-clock time that elapsed from start to finish. User time is the amount of CPU time spent executing user-space code. Sys time is the amount of CPU time spent by the kernel servicing system calls on behalf of the process.
When a process runs multi-threaded workloads across multiple CPU cores in parallel, the CPU times of each core are summed together. For example, a 4-threaded job running for 1 second of wall-clock time on 4 cores can consume 4 seconds of user time.
Use /usr/bin/time -v <command> and look for the 'Maximum resident set size (kbytes)' line, or use /usr/bin/time -f '%M KB' <command> to output peak physical RAM consumption directly.
Using the Bash builtin time, simply write 'time (cmd1 | cmd2)'. For GNU /usr/bin/time, wrap the pipeline in a subshell: /usr/bin/time -v bash -c 'cmd1 | cmd2'.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout