CPU time

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.

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.

  • User time is the amount of time the CPU is busy executing code in user space.
  • System time is the amount of time the CPU is busy executing code in kernel space. This value represents the amount of time the kernel performs work on behalf of the executing process.

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

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:

$ gcc nextPrimeNumber.c -o nextPrimeNumber -lm
$ /usr/bin/time ./nextPrimeNumber 300000070034
Prime number greater than 300000070034 is 300000070043
        0.01user 0.00system 0:00.01elapsed 100%CPU
$

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>
#include <math.h>

int isPrimeNumber(unsigned long int n) {
    unsigned long int limit = ceil(sqrt(n));
    for (int i = 2; i <= limit ; ++i)
        if (n % i == 0) return 0;
    return 1;
}

int main(int argc, char *argv[]) {
    unsigned long int argument = strtoul(argv[1], NULL, 10), n = argument;
    while (!isPrimeNumber(++n));

    printf("Prime number greater than %lu is %lu\n", argument, n);
    return 0;
}

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

References

  • Thimmannagari, Chandra (2005-01-01). CPU Design: Answers to Frequently Asked Questions. Springer. p. 68. ISBN 0-387-23799-2.

Read other articles:

Japanese light novel series Samurai Girl: Real Bout High SchoolCover of the first novel of Samurai Girl: Real Bout High School as published by Fujimi Shoboリアル バウト ハイ スクール(Shoukan Kyoushi Riaru Bauto Hai Sukūru)GenreMartial arts Light novelWritten byReiji SaigaIllustrated bySora InouePublished byFujimi ShoboImprintFujimi Fantasia BunkoMagazineDragon MagazineDemographicShōnenOriginal runJanuary 1997 – July 2010Volumes19 MangaWritten byReiji SaigaI...

 

هذه المقالة بحاجة لصندوق معلومات. فضلًا ساعد في تحسين هذه المقالة بإضافة صندوق معلومات مخصص إليها. كولومبوس أمام الملكة(1843) ,إيمانويل لوتز. هذا المقال عن التسلسل الزمني لحقبة الاستكشاف الأوروبي ابتداءا من 1418 وحتى 1957. القرن الخامس عشر فاسكو دي غاما يصل إلى كالكوتا، رسم لإرنست

 

American physician, engineer, and NASA astronaut Serena M. Auñón-ChancellorNASA portrait, 2009Born (1976-04-09) April 9, 1976 (age 47)Indianapolis, Indiana, U.S.StatusRetiredOccupationFlight surgeonSpace careerNASA AstronautTime in space196 days 17 hours 49 minsSelection2009 NASA GroupMissionsSoyuz MS-09 (Expedition 56/57)Mission insignia Serena Maria Auñón-Chancellor (born April 9, 1976) is an American physician, engineer, and NASA astronaut.[1][2][3] She vis...

1966 compilation album by the Rolling Stones This article is about the Rolling Stones album. For the Outlaws song, see Green Grass and High Tides. Big Hits (High Tide and Green Grass)Original US editionGreatest hits album by the Rolling StonesReleased28 March 1966 (1966-03-28) (US)RecordedLondon, Chicago, and Hollywood, 1964–1965GenreRockLength36:29LabelLondonProducerAndrew Loog OldhamThe Rolling Stones US chronology December's Children (And Everybody's)(1965) Big Hits (H...

 

10A ← 11A → 14A Montevideo Sauce Chamizo San Ramón por (Estación Manga)Área abastecidaMunicipios Sauce, Chamizo, San RamónDistritos Departamento de Montevideo / Departamento de Canelones / Departamento de FloridaDescripciónTipo MetropolitanaSistema STMRamales RamalesExplotaciónFlota Busscar El Buss 320 Mercedes Benz OF-1318 Marcopolo Allegro 1999 Volvo B7R Comil Campione 3.25 Volvo B7R Mascarello Roma Agrale 17.0Operador CUTU (inicios - 2007) UCOT inter (2007 - presente)NotasAndén ...

 

Kampung Rawa beralih ke halaman ini. Untuk desa administratif di Jakarta, lihat Kampung Rawa, Johar Baru. Pemandangan panorama Kampoeng Rawa dengan (dari kiri ke kanan) pusat kerajinan, balai, pendopo, tempat istirahat untuk supir bus, musholla, dan restoran. Gunung Merbabu dan Gunung Telomoyo berada di latar belakang Kampoeng Rawa (disebut juga Kampung Rawa) adalah objek wisata di Ambarawa, Jawa Tengah, yang terletak di sabuk hijau di sekitar Danau Rawa Pening. Dibuka pada Agustus 2012, temp...

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (نوفمبر 2019) جورج أ. دود   معلومات شخصية الميلاد 26 يوليو 1852  مقاطعة ليكومينغ  الوفاة 28 يونيو 1925 (72 سنة)   أورلاندو، فلوريدا  مكان الدفن مقبرة أرلينغتون الوطنية...

 

Town in Vermont, United StatesSharon, VermontTownBaxter Memorial LibraryLocation in Windsor County and the state of Vermont.Location of Vermont in the United StatesCoordinates: 43°46′25″N 72°26′38″W / 43.77361°N 72.44389°W / 43.77361; -72.44389CountryUnited StatesStateVermontCountyWindsorChartered1761Area • Total40.1 sq mi (103.8 km2) • Land39.6 sq mi (102.6 km2) • Water0.5 sq mi (1...

 

Language of the Warao people WaraoNative toVenezuela, Guyana, SurinameEthnicityWaraoNative speakers32,800 (2005–2011)[1]Language familyLanguage isolate or WaroidLanguage codesISO 639-3wbaGlottologwara1303ELPWarao Warao (also known as Guarauno, Guarao, Warrau) is the native language of the Warao people. A language isolate, it is spoken by about 33,000 people primarily in northern Venezuela, Guyana and Suriname. It is notable for its unusual object–subject–verb word orde...

Setting of Psalm 51 by Gregorio Allegri Sistine Chapel Miserere (full title: Miserere mei, Deus, Latin for Have mercy on me, O God) is a setting of Psalm 51 (Psalm 50 in Septuagint numbering) by Italian composer Gregorio Allegri. It was composed during the reign of Pope Urban VIII, probably during the 1630s, for the exclusive use of the Sistine Chapel during the Tenebrae services of Holy Week, and its mystique was increased by unwritten performance traditions and ornamentation. It is written ...

 

Battle of the American Civil War Battle of Princeton Court HousePart of the American Civil WarDateMay 15, 1862 (1862-05-15)–May 17, 1862 (1862-05-17)LocationMercer County, West VirginiaResult Confederate victoryBelligerents United States of America (Union) CSA (Confederacy)Commanders and leaders Jacob Dolson Cox Humphrey MarshallUnits involved Kanawha Division Army of East Kentucky Department of Southwest VirginiaCasualties and losses 113 total23 killed 69 ...

 

4703d Defense Wing Active1952Country United StatesBranch United States Air ForceTypeFighter InterceptorRoleAir DefensePart ofAir Defense CommandMilitary unit The 4703d Defense Wing is a discontinued United States Air Force organization. Its last assignment was with Air Defense Command (ADC)'s Western Air Defense Force at Larson Air Force Base (AFB), Washington. It was established in 1952 in a general reorganization of Air Defense Command (ADC), which replaced wings responsible ...

La tragedia del K2 se refiere a las muertes acaecidas en la temporada de escalada al K2 de 1986 y especialmente al periodo desde el 6 al 10 de agosto, cuando 5 montañeros murieron durante una fuerte tormenta. Otros ocho alpinistas murieron en las semanas precedentes, lo que eleva el total de muertos a trece. El imponente K2, en donde cada año mueren los montañeros por tormentas. Introducción En el corazón de la cordillera del Karakórum, en el norte de Pakistán, en tierra disputada por ...

 

LogoPräsidialamt der Ukraine Das Präsidialamt der Ukraine Daten Ort Kiew, Ukraine Ukraine Architekt Serhij Hryhor'jew Baustil Klassizismus und Ukrainischer Barock Baujahr 1936–1939 Koordinaten 50° 26′ 40,3″ N, 30° 31′ 44,3″ O50.44452777777830.528972222222Koordinaten: 50° 26′ 40,3″ N, 30° 31′ 44,3″ O Besonderheiten Baudenkmal, Regierungsgebäude Blick in die Bankowa-Straße mit dem Haus mit den Chimären li...

 

For the MMO based on the Lego Minifigures theme, see Lego Minifigures Online. This article uses bare URLs, which are uninformative and vulnerable to link rot. Please consider converting them to full citations to ensure the article remains verifiable and maintains a consistent citation style. Several templates and tools are available to assist in formatting, such as reFill (documentation) and Citation bot (documentation). (September 2022) (Learn how and when to remove this template message) Th...

Tournée des Lions britanniques et irlandais 2017 Généralités Sport Rugby à XV Édition 29e Lieu(x) Nouvelle-Zélande Date du 3 juin au 8 juillet 2017 Nations Nouvelle-Zélande Participants 9 équipes Matchs joués 10 Site web officiel www.lionsrugby.com Palmarès Vainqueur Égalité, pas de vainqueur (1-1) Meilleur(s) marqueur(s) Taulupe Faletau (1 essai) Conor Murray (1 essai) Sean O'Brien (1 essai) Rhys Webb (1 essai) Meilleur(s) réalisateur(s) Owen Farrell (45 points) Navigation 2013...

 

Tendency to adopt group beliefs and behaviors Herd mentality (also mob or pack mentality) describes how people can be influenced by the majority. Social psychologists study the related topics of group intelligence, crowd wisdom, groupthink, and deindividuation. History The idea of a group mind or mob behavior was first put forward by 19th-century social psychologists Gabriel Tarde and Gustave Le Bon. Herd behavior in human societies has also been studied by Sigmund Freud and Wilfred Trotter, ...

 

2018 film by Birsa Dasgupta CrisscrossTheatrical release posterDirected byBirsa DasguptaBased onCriss Crossby Smaranjit ChakrabortyProduced byShrikant MohtaMahendra SoniStarringNusrat JahanMimi ChakrabortyJaya AhsanSohini SarkarPriyanka SarkarRidhima Ghosh Arjun ChakrabartyGaurav ChakrabartyMusic byJAM8ProductioncompanyShree Venkatesh FilmsDistributed byShree Venkatesh FilmsRelease date 10 August 2018 (2018-08-10) Running time1h 53mCountryIndiaLanguageBengaliBudget1croresBox of...

Mexican footballer (born 1991) In this Spanish name, the first or paternal surname is Corral and the second or maternal family name is Ang. Charlyn Corral Playing for Mexico in 2014Personal informationFull name Verónica Charlyn Corral Ang[1]Date of birth (1991-09-11) 11 September 1991 (age 32)[1]Place of birth Acolman, State of Mexico, Mexico[2]Height 1.52 m (5 ft 0 in)[1]Position(s) ForwardTeam informationCurrent team PachucaNumber...

 

Town in Capital, DenmarkGillelejeTownBoats in the Gilleleje inner harbourGillelejeLocation in DenmarkShow map of DenmarkGillelejeGilleleje (Capital Region)Show map of Capital RegionCoordinates: 56°07′N 12°19′E / 56.117°N 12.317°E / 56.117; 12.317CountryDenmarkRegionCapital (Hovedstaden)MunicipalityGribskovArea • Urban5.4 km2 (2.1 sq mi)Population (2023)[1] • Urban6,778 • Urban density1,300/km2...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!