CPU time

Last updated
CPU Time on Single CPU Multi Tasking System
.mw-parser-output .legend{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .legend-color{display:inline-block;min-width:1.25em;height:1.25em;line-height:1.25;margin:1px 0;text-align:center;border:1px solid black;background-color:transparent;color:black}.mw-parser-output .legend-text{}
CPU color time for program P1 CpuTimeonSingleCpuMultiTaskingSystem.svg
CPU Time on Single CPU Multi Tasking System
  CPU color time for program P1

CPU time (or process time) is the amount of time that a central processing unit (CPU) was used for processing instructions of a computer program or operating system. CPU time is measured in clock ticks or seconds. Sometimes it is useful to convert CPU time into a percentage of the CPU capacity, giving the CPU usage.

Contents

Measuring CPU time for two functionally identical programs that process identical inputs can indicate which program is faster, but it is a common misunderstanding that CPU time can be used to compare algorithms. Comparing programs by their CPU time compares specific implementations of algorithms. (It is possible to have both efficient and inefficient implementations of the same algorithm.) Algorithms are more commonly compared using measures of time complexity and space complexity.

Typically, the CPU time used by a program is measured by the operating system, which schedules all of the work of the CPU. Modern multitasking operating systems run hundreds of processes. (A process is a running program.) Upon starting a process, the operating system records the time using an internal timer. When the process is suspended or terminated, the operating system again records the time. The total time that a process spent running is its CPU time, as shown in the figure.

User and System time

The process "accounting" done by the Unix family of operating systems includes two components of CPU time. User time and System time reflect the fact that most programs make requests to the operating system while they execute. Input/output operations, such as reading a file or writing to the screen, are done by issuing requests to the operating system, possibly through system calls. I/O and other operations performed by the operating system on behalf of a process constitute system time.

In contrast, elapsed real time (or simply real time, or wall-clock time) is the time taken from the start of a computer program until the end as measured by an ordinary clock. Elapsed real time includes User time, System time, plus time that the process was not running for any reason, such as when its execution was preempted.

Unix commands for CPU time

top's display of the CPU time of various processes on a Unix-like (GNU/Linux) system CPU Time.png
top's display of the CPU time of various processes on a Unix-like (GNU/Linux) system

Unix command top

The Unix command top provides CPU time, priority, elapsed real time, and other information for all processes and updates it in real time.

Unix command time

The Unix command time prints CPU time and elapsed real time for the execution of a Unix command (or pipeline). Note that many command-line shells have their own implementation of this command. To run the Unix program time, we provide its full path, /usr/bin/time:

$ gccnextPrimeNumber.c-onextPrimeNumber $ /usr/bin/time./nextPrimeNumber30000007Prime number greater than 30000007 is 30000023        0.08 real         0.02 user         0.00 sys$

This process took a total of 0.02 seconds of CPU time (User + System). The reported System time is 0.00 seconds, indicating that the amount of System time used was less than the printed resolution of 0.01 seconds. Elapsed real time was 0.08 seconds.

The following is the source code of the application nextPrimeNumber which was used in the above example.

// nextPrimeNumber.c#include<stdio.h>#include<stdlib.h>intisPrimeNumber(unsignedlongintn){for(inti=2;i<=(n>>1);++i)if(n%i==0)return0;return1;}intmain(intargc,char*argv[]){unsignedlongintargument=strtoul(argv[1],NULL,10),n=argument;while(!isPrimeNumber(++n));printf("Prime number greater than %lu is %lu\n",argument,n);return0;}

Functions to get CPU time

Modern CPUs have several clocks and counters, such as the Time Stamp Counter, the High Precision Event Timer, and the Real-time Clock, each with a specialized use. When a program wants to time its own operation, it can use a function like the POSIX clock() function, which returns the CPU time used by the program. POSIX allows this clock to start at an arbitrary value, so to measure elapsed time, a program calls clock(), does some work, then calls clock() again [1] . The difference is the time needed to do the work.

The POSIX function getrusage() returns more than just the CPU time consumed by a process in a POSIX environment. It returns many measurements of a process, often including approximate memory usage and Context switch (scheduling) event counts. Functionality varies across operating systems.

Total CPU time

On multi-processor and multi-core machines, a program can use two or more processors simultaneously in what is called parallel processing. In such situations, a measure of total CPU time is useful, which is the sum of CPU time consumed by all of the processors utilized by the program.

CPU time and elapsed real time

Elapsed real time is always greater than or equal to the CPU time for computer programs which use only one CPU for processing. If no waiting occurs, such as for I/O, and the program's execution is never preempted, elapsed real time and CPU time will be virtually identical.

CPU time and elapsed real time for parallel processing

If a program uses parallel processing, total CPU time for that program is typically more than its elapsed real time. For a program that is able to evenly divide its work across two processors with no overhead in doing so, the value (Total CPU time)/(Number of processors) will be virtually identical to elapsed real time. Here, a processor may be a (single-core) CPU or one core in a multi-core CPU.

Example: A software application executed on a four-core processor creates four Unix processes. If each process is able to execute on a separate processor core, computation proceeds on four processor cores simultaneously. The total CPU time would be, ideally, four times the elapsed real time.

In reality, parallel processing rarely achieves a linear speedup, where the amount of computation per unit time scales up with the number of processors in use. Some embarrassingly parallel problems admit such solutions, but for most, additional work is required to divide up the computation when the program starts, and to combine the results from each processor at the end. The additional work adds to the total CPU time. Frequently, a process finds itself waiting for data from another process before it can continue, which also adds to the total time.

See also

Related Research Articles

<span class="mw-page-title-main">Operating system</span> Software that manages computer hardware resources

An operating system (OS) is system software that manages computer hardware and software resources, and provides common services for computer programs.

A real-time operating system (RTOS) is an operating system (OS) for real-time computing applications that processes data and events that have critically defined time constraints. An RTOS is distinct from a time-sharing operating system, such as Unix, which manages the sharing of system resources with a scheduler, data buffers, or fixed task prioritization in multitasking or multiprogramming environments. All operations must verifiably complete within given time and resource constraints or else fail safe. Real-time operating systems are event-driven and preemptive, meaning the OS can monitor the relevant priority of competing tasks, and make changes to the task priority. Event-driven systems switch between tasks based on their priorities, while time-sharing systems switch the task based on clock interrupts.

<span class="mw-page-title-main">Thread (computing)</span> Smallest sequence of programmed instructions that can be managed independently by a scheduler

In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system. In many cases, a thread is a component of a process.

In computing, particularly in the context of the Unix operating system and its workalikes, fork is an operation whereby a process creates a copy of itself. It is an interface which is required for compliance with the POSIX and Single UNIX Specification standards. It is usually implemented as a C standard library wrapper to the fork, clone, or other system calls of the kernel. Fork is the primary method of process creation on Unix-like operating systems.

RTLinux is a hard realtime real-time operating system (RTOS) microkernel that runs the entire Linux operating system as a fully preemptive process. The hard real-time property makes it possible to control robots, data acquisition systems, manufacturing plants, and other time-sensitive instruments and machines from RTLinux applications. The design was patented. Despite the similar name, it is not related to the Real-Time Linux project of the Linux Foundation.

xargs is a command on Unix and most Unix-like operating systems used to build and execute commands from standard input. It converts input from standard input into arguments to a command.

time (Unix) Command in Unix and Unix-like operating systems

In computing, time is a command in Unix and Unix-like operating systems. It is used to determine the duration of execution of a particular command.

In computing, POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a programming language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time. Each flow of work is referred to as a thread, and creation and control over these flows is achieved by making calls to the POSIX Threads API. POSIX Threads is an API defined by the Institute of Electrical and Electronics Engineers (IEEE) standard POSIX.1c, Threads extensions .

In computer science and software engineering, busy-waiting, busy-looping or spinning is a technique in which a process repeatedly checks to see if a condition is true, such as whether keyboard input or a lock is available. Spinning can also be used to generate an arbitrary time delay, a technique that was necessary on systems that lacked a method of waiting a specific length of time. Processor speeds vary greatly from computer to computer, especially as some processors are designed to dynamically adjust speed based on current workload. Consequently, spinning as a time-delay technique can produce inconsistent or even unpredictable results on different systems unless code is included to determine the time a processor takes to execute a "do nothing" loop, or the looping code explicitly checks a real-time clock.

top (software) Task manager program found in many Unix-like operating systems

top is a task manager or system monitor program, found in many Unix-like operating systems, that displays information about CPU and memory utilization.

stat (system call) Unix system call

stat is a Unix system call that returns file attributes about an inode. The semantics of stat vary between operating systems. As an example, Unix command ls uses this system call to retrieve information on files that includes:

Signals are standardized messages sent to a running program to trigger specific behavior, such as quitting or error handling. They are a limited form of inter-process communication (IPC), typically used in Unix, Unix-like, and other POSIX-compliant operating systems.

<span class="mw-page-title-main">Unix time</span> Date and time representation system widely used in computing

Unix time is a date and time representation widely used in computing. It measures time by the number of non-leap seconds that have elapsed since 00:00:00 UTC on 1 January 1970, the Unix epoch. In modern computing, values are sometimes stored with higher granularity, such as microseconds or nanoseconds.

<span class="mw-page-title-main">O(1) scheduler</span> Historical Linux 2.6 kernel process scheduler

An O(1) scheduler is a kernel scheduling design that can schedule processes within a constant amount of time, regardless of how many processes are running on the operating system. This is an improvement over previously used O(n) schedulers, which schedule processes in an amount of time that scales linearly based on the amounts of inputs.

In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.

The proc filesystem (procfs) is a special filesystem in Unix-like operating systems that presents information about processes and other system information in a hierarchical file-like structure, providing a more convenient and standardized method for dynamically accessing process data held in the kernel than traditional tracing methods or direct access to kernel memory. Typically, it is mapped to a mount point named /proc at boot time. The proc file system acts as an interface to internal data structures about running processes in the kernel. In Linux, it can also be used to obtain information about the kernel and to change certain kernel parameters at runtime (sysctl).

In computing, exec is a functionality of an operating system that runs an executable file in the context of an already existing process, replacing the previous executable. This act is also referred to as an overlay. It is especially important in Unix-like systems, although it also exists elsewhere. As no new process is created, the process identifier (PID) does not change, but the machine code, data, heap, and stack of the process are replaced by those of the new program.

In computer science and computer programming, system time represents a computer system's notion of the passage of time. In this sense, time also includes the passing of days on the calendar.

Spawn in computing refers to a function that loads and executes a new child process. The current process may wait for the child to terminate or may continue to execute concurrent computing. Creating a new subprocess requires enough memory in which both the child process and the current program can execute.

Getopt is a C library function used to parse command-line options of the Unix/POSIX style. It is a part of the POSIX specification, and is universal to Unix-like systems. It is also the name of a Unix program for parsing command line arguments in shell scripts.

References