Chapter 4: Linux Advanced Commands
4.12 Monitoring: top and htop
In short: Use top or htop where installed to observe task activity, system load, and memory. Compare samples taken during the reported slowdown.
Friends, when a server becomes slow, the first question is – who is eating the CPU and how much RAM is left? top is the live dashboard, and htop is its colourful, easier brother.
मित्रांनो, सर्व्हर स्लो झाला की पहिला प्रश्न – CPU कोण खातो आणि RAM किती उरली? top हा लाइव्ह डॅशबोर्ड आहे, आणि htop त्याचा रंगीत, सोपा भाऊ.
दोस्तों, सर्वर स्लो हुआ तो पहला सवाल – CPU कौन खा रहा है और RAM कितनी बची है? top लाइव डैशबोर्ड है, और htop उसका रंगीन, आसान भाई.
Check which process viewer your lab already provides. The examples use Linux procps top where installed and describe optional htop controls. The bounded workload also reports its own CPU time.
| In top | Action |
|---|---|
P / M |
Sort by CPU / memory |
h / ? |
Read help for this viewer |
1 |
Toggle individual logical CPU display |
q |
Quit |
Read load averages, process %CPU, %MEM, resident memory, and CPU time accounting separately. An elevated wa value merits an I/O investigation with other measurements.
Ravindra Bagale's Tip
Compare Linux load averages with available CPU capacity and the recent workload. Runnable and uninterruptible tasks both contribute. A higher I/O-wait figure calls for checking the tasks and relevant device or filesystem metrics.
Ravindra Bagale's Tip – मराठी
Linux load averages सोबत उपलब्ध CPU क्षमता आणि त्या वेळचे workload पाहा. Runnable आणि uninterruptible tasks दोन्ही load मध्ये मोजले जातात. I/O wait वाढला तर tasks आणि संबंधित device चे metrics तपासा.
Ravindra Bagale's Tip – हिंदी
Linux load averages के साथ उपलब्ध CPU क्षमता और उसी समय का workload देखें। Runnable और uninterruptible tasks दोनों load में गिने जाते हैं। I/O wait बढ़ने पर tasks और संबंधित device की measurements जाँचें।
Lab
खालील workshop lab मध्ये दोन छोटे processes चालवा. एक गणना करतो आणि दुसरा थांबतो. दोघांचा elapsed time आणि CPU time मोजा. दोन्ही processes स्वतः पूर्ण होतात.
Translate a report of slowness into measurable symptoms
The Mauli workshop runs an inspection summary that usually takes a few seconds. During one shift, the operator says that the worksheet page takes much longer to open. The monitoring display also shows a larger number than usual beside one process. Those observations might be related, but you need to connect their times, work, and scope. Did the affected request wait for CPU time, for a file, for a database, or for something outside the machine? A process viewer helps you ask a narrower question before deciding whether to change resources or stop anything.
A process is an executing program instance identified by a process ID, or PID. A process can run one or more threads, which are units the system can schedule. The scheduler chooses which eligible threads receive CPU time. An application can be idle, actively computing, asleep waiting for an event, or temporarily waiting for an operation that cannot be interrupted in the ordinary way. A displayed process state is a snapshot at one moment, and the same process can move through multiple states between two samples.
top shows the system summary and a list of tasks at repeated intervals. Linux has different implementations, and the commands discussed here refer to the procps version when its particular options matter. htop is an optional interactive process viewer that can display similar observations with a different layout, meters, and selected filtering tools. Its presence depends on the environment. Both let you inspect resources without changing running jobs. In this lesson the objective is observation and interpretation. It is possible to complete the worked exercises without installing an extra viewer or terminating a process you did not start.
Use two reference points. The first is a measurement of the issue itself, such as how long a known report took or the status of a known application request. The second is a system or process sample between the start and end of that issue. A lone screenshot taken afterward can miss a brief spike. Record the time, hostname or environment, workload being measured, and scope of the tool. That makes it possible for someone else to evaluate whether a visible measurement explains the user's problem.
Read CPU activity, load averages, and elapsed time as different quantities
Elapsed time is the time an observer waits from start to finish. CPU time is time a thread or process actually spends executing on a CPU, including portions accounted to its operating system work. A process can take five seconds to finish and use very little CPU if it spent most of the interval sleeping or waiting on another resource. Conversely, a process with several executing threads can add up more CPU time than elapsed time across those threads. Ask whether a displayed value is a total amount of time, a fraction of a short sampling interval, or a smoothed measure covering a longer period.
The procps top task column %CPU reflects CPU use across recent updates. The display can use a per-CPU basis or a normalization across all CPUs, depending on mode. In the commonly used per-CPU convention, one fully occupied logical CPU is approximately one hundred percent for that workload. A multithreaded process can exceed one hundred percent in that convention. Whole-machine summary percentages distribute time across the observed CPUs, so they can use a different basis from a task row. An apparent disagreement can be a denominator difference. Confirm the mode and interval before comparing percentages between tools.
Consider a four-vCPU guest. A single-threaded calculation may occupy one logical CPU nearly continuously while the other three are mostly idle. A task row can approach one hundred percent on a per-CPU basis. The aggregate non-idle work attributable to that calculation is roughly one quarter of a four-CPU total in a steady interval. Adding more healthy idle CPUs does not make a single-threaded calculation automatically parallel. If this one task serves a critical request, its progress can still be limited even with a low whole-machine average. Inspect per-CPU and per-process activity as well as the actual task structure.
Linux load averages are smoothed measures of demand from runnable tasks and tasks in uninterruptible sleep. The three figures commonly shown correspond to one-, five-, and fifteen-minute periods. They are not percentages. A task can contribute to load when it cannot run because it is waiting in an uninterruptible state. This is why the values are not simply an average of recent process CPU utilization. A high short-period value relative to the longer-period values can suggest an increase in recent demand. A brief change can persist in those smoothed numbers after the workload exits.
For example, a system with two CPUs could show load averages of 1.5, 0.7, and 0.3. That pattern suggests a recent increase in demand relative to the longer periods. It alone does not certify healthy response times or say which resource the tasks needed. A value below two can coexist with a single busy thread delaying a workload. A value above two could occur with many runnable tasks or with blocked tasks contributing. Use the visible capacity and requirements of the workload, compare task states and recent CPU delivery, and corroborate with the user-facing timing. One ratio is useful context, not a universal threshold.
A guest or container also sees only its own context. A service may have a CPU quota, or a virtual machine may be configured for a particular CPU model. On AWS burstable instances, check the applicable credit mode and credit metrics if a long-running CPU pattern looks different from expected. CloudWatch credit measurements describe another level of evidence and have their own periods. A short top sample inside a machine does not directly reveal a credit balance. Align the observed time and unit across monitoring sources before interpreting the relationship.
Read one Linux snapshot from summary to process rows
On a prepared Linux workstation, open top and give it several updates. The screen begins with overall summaries, including uptime and load, task counts, CPU time categories, and memory. Below that are task rows. Learn which part of the display answers the immediate question. If a task appears at the top of a list sorted by CPU, it is the largest visible value in that view. Sorting does not by itself establish whether it caused the user's slowdown. Compare it with process identity, counters over time, and relevant application behavior.
On procps top, uppercase P selects CPU sorting and uppercase M selects memory sorting. Pressing 1 toggles a per-CPU view under the usual display settings. Press h or the question mark to consult the current help, and q to close the viewer. Closing the viewer does not stop the processes it displayed. A terminal may show different controls or columns based on the current version, operating system, or saved viewer settings. A minimal image may omit top altogether. Check the installed command's help instead of assuming its presence or changing packages on a shared machine.
| Observation | Useful first reading | Question to check next |
|---|---|---|
%CPU high on a task across multiple samples | The task received CPU time during those intervals. | Does its work match the delayed request, and what basis does the display use? |
TIME+ increasing consistently | The task's accumulated CPU time grows while observed. | How much changed over the same wall-clock interval? |
RES high for a process | Many bytes are resident in physical memory for that process view. | How much is shared, and what memory does the machine have available? |
wa elevated in the CPU summary | The accounting shows time attributed to I/O waiting under the OS rules. | Which tasks and devices were waiting during the affected interval? |
| Tasks fluctuate between running and sleeping | The display is sampling changing execution states. | Can you correlate a series of samples with slower work? |
Time accounted as I/O wait, often labeled wa, is a clue to investigate waiting work. It is not a direct measurement of disk speed or a diagnosis of one failing device. Linux's accounting has documented limitations, especially with multiple CPUs. A CPU can execute a different task while one waits for I/O. Check which process was blocked and compare available I/O metrics for the appropriate device and interval. A web request can also wait on a remote service without producing an obvious local disk-wait signal.
Some brief state letters can help direct investigation. In the common Linux process state display, R means running or runnable, S is interruptible sleep, and D is uninterruptible sleep. A sleeping task may be waiting normally for work. D often points toward a blocking kernel operation, and a snapshot does not identify the resource on its own. Z identifies a zombie, a process that has exited but whose parent has not yet collected its status. It is not a process continuously consuming application CPU. Read the documentation and surrounding evidence before responding to a single state letter.
Compare memory numbers using their scope and units
RAM is physical memory available for currently usable data and work. A process's virtual address space can include mappings that are shared, backed by files, or not resident. Procps top commonly names virtual size VIRT and resident memory RES. A process with a virtual size of 4 GiB and a resident size of 120 MiB is not necessarily using 4 GiB of physical memory. Compare the columns using the displayed units. Resident totals from different processes can overlap when they map the same physical pages, so adding all their displayed resident sizes may count the same data more than once.
Use free -h on a Linux lab to read the memory view through another command. Its available field estimates how much memory can be used for new applications without swapping, incorporating reclaimable cache and other considerations. Its free field only describes memory currently unused, which can be much smaller. Linux can use spare capacity for caching useful data. A small free number is not enough evidence of a shortage if available is still healthy for the demonstrated workload. Check the behavior over time and the actual allocation requirement.
free -h
uptime
total used free buff/cache available
Mem: 7.7Gi 3.2Gi 300Mi 4.2Gi 4.5Gi
The output is a simplified teaching example and omits some displayed fields and the swap row. It also omits the uptime output, which commonly includes load figures. The important distinction is that 300 MiB is immediately unused while the estimated available amount is much larger in this illustration. A program requesting 500 MiB can therefore be compatible with the overall picture, depending on conditions and its own resource limits. A service or container with a lower configured memory limit can still face pressure even when the host has capacity. Match the measurement to the environment where that service runs.
Swap is a place for the operating system to keep some memory pages outside RAM, where supported and configured. Previously used swap space does not establish that active swapping caused the current slowdown. Compare recent paging or memory pressure evidence, application health, and memory available to the workload. A filesystem full of files is a different issue from insufficient reclaimable process memory. Earlier storage observations such as df describe a mounted filesystem. They should not replace a memory diagnosis, even when a memory-backed filesystem is involved.
Compare two known processes that finish on their own
The workshop will simulate two tasks lasting about six seconds. One performs small calculation bursts separated by sleep intervals. The other simply sleeps for the whole interval. Both take time to finish as measured outside, but their CPU times should differ. Run this only in your own practice environment, with Bash and Python 3 available. The experiment uses two short local children and no remote workload. It performs no network requests, creates no permanent jobs, and avoids leaving an unbounded background process running.
The program below reports its own elapsed time and process CPU time after it finishes. The CPU clock measures active CPU usage by this process rather than wall time. During a burst the loop repeatedly computes a small arithmetic value, and the burst's wall deadline keeps that work bounded. Each burst is followed by a pause. The script's overall monotonic deadline is based on a clock suitable for measuring durations even if someone adjusts wall-clock time. The result demonstrates relative usage. It is not a benchmark of the processor, because the operating system and competing work can affect the numbers.
monitor_lab=$(mktemp -d) || exit 1
printf 'Lab directory: %s\n' "$monitor_lab"
cat > "$monitor_lab/workload.py" <<'PYTHON'
import sys
import time
mode = sys.argv[1]
start = time.monotonic()
cpu_start = time.process_time()
deadline = start + 6
if mode == "bursts":
value = 0
while time.monotonic() < deadline:
burst_end = min(deadline, time.monotonic() + 0.04)
while time.monotonic() < burst_end:
value = (value + 17) % 1009
time.sleep(min(0.06, max(0, deadline - time.monotonic())))
elif mode == "sleep":
time.sleep(max(0, deadline - time.monotonic()))
else:
raise SystemExit("expected bursts or sleep")
print(f"{mode}: elapsed={time.monotonic() - start:.2f}s cpu={time.process_time() - cpu_start:.2f}s")
PYTHON
python3 "$monitor_lab/workload.py" bursts > "$monitor_lab/bursts.txt" &
bursts_pid=$!
python3 "$monitor_lab/workload.py" sleep > "$monitor_lab/sleep.txt" &
sleep_pid=$!
printf 'Practice PIDs: bursts=%s sleep=%s\n' "$bursts_pid" "$sleep_pid"
ps -p "$bursts_pid,$sleep_pid" -o pid=,stat=,etime=,time=,comm=
if [ "$(uname -s)" = Linux ] && top -V 2>/dev/null | grep -qi procps; then
top -b -n 2 -d 1 -p "$bursts_pid,$sleep_pid" > "$monitor_lab/top-samples.txt"
fi
wait "$bursts_pid"
wait "$sleep_pid"
cat "$monitor_lab/bursts.txt" "$monitor_lab/sleep.txt"
bursts: elapsed=6.00s cpu=2.35s
sleep: elapsed=6.00s cpu=0.00s
The example omits the generated directory, process IDs, and ps snapshot. Your timings vary. Both tasks should have elapsed times around six seconds or greater. The process doing bursts should normally use noticeably more CPU time than the sleeper. The sleeper can still have a small amount of CPU time from preparing the wait or recording the result. If one task was delayed by host scheduling, compare relative time without expecting a precise percentage. The measurement starts inside the program and differs slightly from lifetime measured by ps.
The first $! is saved before launching the second job. Each value is the PID the shell can use to wait for its own child. The ps command requests only these two process IDs. Its stat field is state and can include other flags, etime shows elapsed time, and time shows CPU time. At the very beginning the processes may have accumulated too little time to make a large visible difference in a single snapshot. The final Python results provide independent evidence about the full course of each process. The shell waits for each child to end naturally, so no signal is needed.
On Linux with procps top, the conditional command saves two screens to top-samples.txt. -b requests batch mode, -n 2 bounds the number of updates, -d 1 sets the nominal seconds between them, and -p selects just our PIDs. This version check deliberately skips a different top implementation. Open the sample file in the scratch directory if the command generated it. The earlier observation interval can be sensitive to startup timing, so compare the later task rows and the final CPU time results. If the sample does not contain a task, check whether the process finished before the capture or the command supports the exact flags.
For a measured example of 2.35 seconds of CPU time over 6.00 elapsed seconds, the quotient is about 0.39 of one CPU across the whole run. In the single-CPU convention that corresponds to about 39 percent averaged over the measured lifetime. A task row sampled during one active burst or one pause can show a different value. The instantaneous state could be sleeping and the recent interval could still include earlier work. Repeated sampling and the full-run accounting provide complementary views.
This is a deliberately small demonstration. It may leave little visible change in the machine-wide load numbers, especially on a busy or many-core system. That is expected. A six-second job has a very different window from the smoothed one-, five-, and fifteen-minute demand figures. The appropriate checks are the two PIDs, their sample states where available, and the significantly different accumulated CPU time over similar elapsed duration. Do not increase the load or repeatedly spawn uncontrolled jobs to force the overall display to move.
Observe a bounded memory allocation instead of trying to fill RAM
Use an optional companion experiment to see what a small allocation means for one process. The script records a peak resident value reported for itself, creates a 12 MiB byte array, touches each page, and records the value again. A memory page is a unit the operating system uses to map chunks of an address space. Merely reserving a virtual address range can have a different effect from writing each of its pages. This fixed-size example completes immediately and holds far less than the memory of an ordinary practice computer. Skip it if the lab is configured with an unusually tight memory limit.
python3 - <<'PYTHON'
import mmap
import resource
before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
data = bytearray(12 * 1024 * 1024)
for offset in range(0, len(data), mmap.PAGESIZE):
data[offset] = 1
after = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print(f"requested bytes: {len(data)}")
print(f"peak resident before: {before}")
print(f"peak resident after: {after}")
PYTHON
The requested byte count is 12582912. The other numbers depend on the Python and operating system overhead and units. This is a peak resident measurement. It captures the largest reported value seen during this process's lifetime so far and can differ from the instantaneous row in top. On Linux the underlying usage interface documents its peak resident field in KiB. Platforms can report different units, so compare these two values only in the same environment and read the local documentation before converting them. The example is an observation about this one Python process, not an estimate of the host's total RAM usage.
The array remains referenced until the short command ends. The loop writes one byte per page through a normal path. On a typical Linux machine the after value should be noticeably larger. Exact differences need not equal the full allocation because accounting, allocator reuse, and startup peaks can influence the observation. If a current resident value later fell when resources were released, the earlier peak could still remain large. An ongoing memory issue should be investigated with multiple current samples, the workload's limits and logs, and longer-term trends. A one-time peak answers what was observed in one process lifetime.
These two fixtures separate work dimensions. The CPU example reports time that an active calculation spent executing. The memory exercise reports bytes made addressable by the application and a process's resident measure. A program can reserve memory while sleeping, or use CPU intensively with little memory. Sorting a viewer by CPU and by memory can therefore surface different tasks at the same moment. Before deciding which row to investigate, connect the user's symptom with the task's timing, the resource it needs, and any policy that constrains it.
Inspect the same evidence in htop when it is available
On a prepared Linux lab with htop installed, start it normally from your terminal. It can show CPU meters, memory and swap meters, and rows that may include user, PID, state, and CPU or memory figures. Your installed version and settings determine the columns and their labels. The search and filter controls can help locate a known process name when many tasks are present. Searching for a name can show several entries from different owners or workloads, so use the exact PID and timestamp when comparing evidence from two tools.
The labels along htop's bottom edge show actions such as help, search, filter, or changing sort. In commonly used versions F6 chooses a sort field, and F10 or q exits. Some terminals intercept function keys, so read the viewer's help and use documented alternatives. Keep the exercise read-only. The viewer can also expose process-management controls, but pressing an action on a selected row can affect a running service. Our two training children exit by design and do not require that action. If htop is not present, compare the saved procps top samples and Python numbers instead.
A process viewer can present threads as well as processes. Two rows with the same program name might be threads within one process, separate worker processes, or two unrelated copies of a tool. Some views show both a process summary and individual execution threads. Before adding rows together, check what each one counts and whether the same activity appears at more than one level. The command line can help identify the purpose of a process, but rows can include arguments that contain sensitive data. Review and limit any captured output before sharing it with a teammate.
If the task you want has already ended, it may not appear in either interactive viewer. You can use the episode's saved logs and time-stamped measurements instead of guessing its old PID. PIDs can be reused after a task exits. An instruction that targets a stale number can affect a different process. This is one reason the example starts its own identified jobs in one shell and waits for them directly. At work use the authorized service manager or owner procedure for any action on a running job, and confirm the identity from fresh evidence.
Check whether the application can use the capacity you see
A resource monitor can show the processors visible to a machine while a service is allowed to use only a fraction of them. Linux control groups, often called cgroups, group processes and let administrators apply resource policies. CPU and memory limits can differ by service, container, and nesting level. If four CPUs appear in the overall display, four CPUs worth of execution time may still be unavailable to a particular group. Identify the workload's effective limits before promising that spare host capacity solves its delay.
Read a worked quota example. On Linux cgroup v2, an applicable cpu.max setting represented by two values such as 20000 100000 describes a maximum of 20000 microseconds of CPU time over a period of 100000 microseconds for that group. Dividing gives 0.2 of one CPU's worth of execution over time under that quota. The unit does not place the group permanently on one particular core. The scheduler can allow the group to use capacity in bursts within the available policy and then limit it for the rest of a period. A long job can therefore be slow while the machine-wide CPU meter retains spare capacity.
For a hypothetical CPU job that needs about one second of CPU time, that quota would extend a sustained run across roughly five seconds of wall time under idealized conditions. Extra waiting, time used by other jobs in the group, or stricter parent controls can change the observed duration. The arithmetic is a prediction for the specific configuration, not a replacement for measuring the request. An actual deployment should name the cgroup and its parent relationships through its approved tools and configuration. This lesson makes no quota changes to demonstrate the concept.
A similar issue applies to a service's memory limit. Suppose the host reports 4.5 GiB available, while the workload's group is limited to 512 MiB and normally uses 430 MiB. A new 150 MiB requirement could put pressure on the group even though the host can provide that many bytes to unconstrained work. Memory reclaim and sharing can make measured outcomes more complex than the simple sum, so inspect the actual group events and service logs instead of relying on subtraction alone. Resource availability is meaningful only along with its scope.
Virtual machines can supply another kind of boundary. Procps top may show st, CPU time accounted as stolen by the hypervisor in applicable guests. A change in that metric can help frame a virtualization investigation, but it does not show which instance, setting, or provider activity was responsible. Burstable instance credit measures are another separate source, shown for supported EC2 types. If those matters are relevant, align timestamps and use the provider's documented per-instance metrics along with the workload's local sample. Neither an I/O wait percentage nor a single CPU sample can substitute for that information.
When you write a handover, say which denominator you used. “Worker used about 40 percent of one CPU over six elapsed seconds” is different from “the four-core host averaged 40 percent busy” or “the group used most of its allowed period.” Each statement can be true in its own setting. Comparing them requires matching units, limits and time. This habit turns a dashboard screenshot into evidence another engineer can evaluate.
Follow a symptom through several measurements
Imagine that the workshop requests at 09:10 took twelve seconds instead of their usual one. A process named report-worker showed nearly one hundred percent CPU repeatedly on one logical CPU. The system summary averaged 25 percent active work on a four-vCPU guest. Per-CPU display showed one busy logical CPU and three mostly idle ones. The application's own log placed the slow report within that same interval. Those observations support a hypothesis of a single busy execution path. The next check would be whether that process and thread handled the reported work and whether the calculation can be made more efficient. Adding a fifth or sixth idle CPU on the same guest may not make that sequence faster.
For a second observation, suppose load rose while CPU execution was modest and several related workers appeared in D state during storage activity. In that case check the storage device serving the files involved and compare its I/O latency or queue measures over the same interval. A large wa percentage alone does not point at a uniquely bad disk. It can reflect waiting while CPUs have no other runnable work, and additional independent CPU work can change that proportion without making the device faster. Confirm specific evidence about the underlying resource. A data volume, a network filesystem, and a remote database can be relevant to different transitions.
For a third observation, suppose the displayed free RAM dropped while cached memory grew and reported available capacity remained fairly stable. The machine may be using memory effectively to cache data rather than developing a memory shortage. Compare that case with a workload that repeatedly has little available memory, frequent paging activity, and delays when it requests new storage for data in memory. Make observations over the actual time of the slowdown. Watch the service's own limits and memory failures when it is constrained independently of the whole host. The pressure symptoms can lead to different actions even when a screenshot shows the same free amount in both cases.
When the vmstat command is present on a Linux lab, it can supply short repeated observations. The next command takes three displays with one-second spacing between updates. On the documented procps implementation the first interval statistics can reflect averages since boot, whereas later rows reflect their just-completed intervals. Some values, such as process counts and memory summaries, are instantaneous even in the first display. Compare rows two and three for a short-term check and read the relevant field definitions before applying units.
vmstat 1 3
The r column describes runnable processes and the b column describes processes blocked on I/O according to the tool's definitions. The swap columns si and so describe activity rates. They are different from a total amount of already used swap. A rising runnable count and busy processors can support a CPU queue hypothesis, while repeated blocked activity and a measured storage issue can support a different hypothesis. The report is system-wide, so correlate it with the processes you believe are involved. Many standard installations have some version of these utilities, but the actual flags and measurements depend on the system.
Some Linux kernels expose Pressure Stall Information, or PSI. With approved access, files such as /proc/pressure/memory can describe time during which tasks were stalled by pressure on a resource. This is a different measurement from memory bytes used or a CPU percentage. Kernel documentation defines each line and its time windows. Notice which boundary produced the number before comparing it with a process row from top. A host-level view can include other unrelated workloads, while a service's cgroup can have its own constraints. Use measurements of the right component to investigate the issue the workshop actually reported.
For any incident, write a compact timeline. Include the user's first report, a known healthy baseline if available, the tool and interval used to observe symptoms, and any narrow operation that changed the result. Capture repeated observations before and after a controlled change. The monitoring viewport is not a license to stop the first program in a sorted list. A backup or scheduled export may legitimately use resources at that time. Verify the owner and expected effect before changing the workload or its resource policy.
Record results and verify your interpretation
For the first task, run the paired workload and write down both measured elapsed times and CPU times. Predict the difference before running them. A typical result shows that both tasks lasted about six seconds, while the burst task used significantly more CPU than the sleeping task. Compute each CPU-to-elapsed quotient and state explicitly that the comparison uses one process and one lifetime rather than the whole machine's sample. If a top sample shows an unexpected state, use the final CPU time and the timing of each burst to explain why one snapshot need not tell the whole story.
For the second task, compare a resident or peak resident value with a logical allocation in the companion memory exercise. Explain that the request of 12 MiB measures bytes requested in the program, while the quality of the system observation depends on its accounting, units, sampling and other allocations. Record the reported before and after values, and specify the platform. If the unusual result gives two equal values, note that it is a peak metric and report the result without inventing a higher number. Compare the relevant documentation and the workload's observations to understand what could account for the result.
For the third task, write the next evidence request for one of the three incidents. In the single-threaded case, identify the worker and workload that coincide with the slow response. In the I/O case, request measurements of the specific storage or network path and the tasks waiting on it. In a memory case, request current available memory, pressure or paging activity, and actual limits for the affected service. Each response should use at least two independent observations. Avoid calling a guessed resource change a verified fix.
If you repeat the CPU lab, use a new scratch directory so you do not mix samples from different runs. Do not save other users' command lines in a shared artifact. The lab stores only its known files and lets both test processes exit. The cleanup below removes the exact paths after your comparison. If a batch capture did not run, there is no sample file to remove. The optional memory example creates no file. Check the generated directory name before cleanup and keep only the notes you intended to share.
if [ -n "${monitor_lab:-}" ] && [ -d "$monitor_lab" ]; then
printf 'Cleaning lesson fixtures from %s\n' "$monitor_lab"
rm -f -- "$monitor_lab/workload.py" "$monitor_lab/bursts.txt" \
"$monitor_lab/sleep.txt" "$monitor_lab/top-samples.txt"
rmdir -- "$monitor_lab"
fi
unset monitor_lab bursts_pid sleep_pid
Explain a monitoring result with its denominator
Interview question. Why can a process show 100 percent CPU while a four-vCPU host summary shows about 25 percent?
A per-CPU task display may express the task as a proportion of one logical CPU. One task consuming one complete CPU on a guest with four accounts for roughly a quarter of the total capacity if the others are largely idle. Confirm the monitor's mode, task selection and interval, then connect that work with the service symptom.
Interview question. Is a load average above the number of vCPUs a disk diagnosis?
Load counts eligible tasks and some uninterruptible wait states and smooths them over several periods. A large value can suggest runnable pressure, waiting work, or a combination. Inspect CPU delivery, relevant process states and resource-specific metrics before assigning a cause.
Quiz. Why does the six-second sleeper show very little process CPU time?
Elapsed time includes the period spent waiting. Process CPU time measures execution by the process. Sleeping lets the scheduler run other work, so six seconds can pass with only a small CPU expense for setup and reporting.
Quiz. Which Linux memory figure estimates headroom for a new application without swapping?
The available field of free estimates that headroom, factoring in potentially reclaimable cache and other kernel accounting. The immediately unused free field is a different quantity. A workload can still have a lower independent limit, so verify the scope of the estimate.
Quiz. Which is the better evidence for an intermittent slow request: a single process screenshot afterward or measurements spanning the request?
Measurements spanning the request supply timing and can show whether relevant resources were busy or tasks were waiting at the same time. A later snapshot can help identify remaining state but might miss the transient cause. Include a time and process or service identity with the observed data.
Revision cards
Ask which time and which CPU basis
Separate process CPU time, wall duration, task sampling percentages, and load averages. Write the interval with the result.
Look past the largest number
Use the task's owner, identity and relation to the delayed request. Corroborate CPU, memory or I/O evidence with an independent observation.
Resource state and safe action are separate
A busy process can be doing planned work. Use the established owner and service procedure before interrupting it. The training jobs finish by themselves.
Primary references
- Procps top manual for task modes, refreshes, and fields
- Htop project manual for display and controls
- Linux kernel load-average interface
- Linux CPU time accounting and I/O wait limitations
- Procps free and available-memory documentation
- Procps vmstat sampling intervals and statistics
- Linux process usage interface and peak resident values
- Linux kernel documentation for Pressure Stall Information
- AWS burstable CPU credit measures
- Linux cgroup v2 CPU and memory controls