Chapter 9 Times and Timers Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.

Slides:



Advertisements
Similar presentations
Unix Time Functions CNS The basic Linux (and Unix) time service counts the number of seconds that have passed since January 1, 1970 (UTC). These.
Advertisements

System Files and Process Environment Password file Group file System identification Time Process environment.
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
The Process Control Block From: A Process Control Block (PCB, also called Task Control Block or Task Struct) is.
I/O Multiplexing Road Map: 1. Motivation 2. Description of I/O multiplexing 3. Scenarios to use I/O multiplexing 4. I/O Models  Blocking I/O  Non-blocking.
Dale Roberts Basic I/O – scanf() CSCI 230 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Department of.
An Introduction to Programming with C++ Fifth Edition
1 Homework / Exam HW7 due class 25 Exam 3 - class 26 –Open Book, Open Notes –Covers up through end of K&R 7 –and Appendix B Standard Library –Plus UNIX.
TDC561 Network Programming Camelia Zlatea, PhD Week 3: Unix Asynchronous Events; Signals and Alarms API.
CSE 222 Systems Programming Time, Errors, and File Access Dr. Jim Holten.
Timers Timer – Keeps track of the passage of time Simple Timer – Measures elapsed time, reporting it when queried Interval Timer – –Generates an interrupt.
Time Measurement October 25, 2001 Topics Time scales Interval counting Cycle counters K-best measurement scheme class18.ppt.
Exec function Exec function: - replaces the current process (its code, data, stack & heap segments) with a new program - the new program starts executing.
Ceng Operating Systems Chapter 2.1 : Processes Process concept Process scheduling Interprocess communication Deadlocks Threads.
Signal Signal : - is a notification sent to a process to notify it of some event - interrupts whatever the process is doing and force it to handle a signal.
Timers Timer – Keeps track of the passage of time Simple Timer – Measures elapsed time, reporting it when queried Interval Timer – –Generates an interrupt.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 26P. 1Winter Quarter Handy Board Lecture.
Week 8 - Friday.  What did we talk about last time?  String to int conversions  Users and groups  Password files.
1 The UNIX date command myclock.cpp example The C/C++ time() and ctime() functions myclock2.cpp example Inline function definitions Inline class member.
1 CS 162 Introduction to Computer Science Chapter 5 ASCII to Integer Conversion Herbert G. Mayer, PSU Status 11/9/2014.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
4061 Session 17 (3/19). Today Time in UNIX Today’s Objectives Define what is meant when a system is called “interrupt-driven” Describe some trade-offs.
Php – 日期與時間 php.ini (in C:\xampp\php\) date.timezone = Asia/Taipei.
MPI and High Performance Computing: Systems and Programming Barry Britt, Systems Administrator Department of Computer Science Iowa State University.
CS102 Introduction to Computer Programming Chapter 4 Making Decisions.
1 Chapter 2.1 : Processes Process concept Process concept Process scheduling Process scheduling Interprocess communication Interprocess communication Threads.
Chapter 6 UNIX Special Files Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.
Chapter 2 Simple Data Types By C. Shing ITEC Dept Radford University.
Chapter 2 Programs, Processes, and Threads Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Timers and Clocks.
System calls for Process management
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Linux Processes Travis Willey Jeff Mihalik. What is a process? A process is a program in execution A process includes: –program counter –stack –data section.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 26P. 1Winter Quarter Handy Board Lecture 26.
Spring 2005, Gülcihan Özdemir Dağ Lecture 8, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 8 Outline 8.1 Declaring.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Timers and Clocks II.
Operating Systems Recitation 4, April th, 2002 Signals.
How to design and code functions Chapter 4 (ctd).
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Timers and Clocks.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Interacting with Unix. Getting the Process ID u Synopsis #include pid_t getpid(void); u Example: #include int main(){ pid_t n = getpid(); printf("Process.
Lecture 2a: Performance Measurement. Goals of Performance Analysis The goal of performance analysis is to provide quantitative information about the performance.
1 Inter Process Communication & Timers. 2 Time.h (page R:Ch9 pp ) #include time_t time(time_t *calptr); Epoch: 00:00 (midnight), Jan 1, 1970 GMT.
1/15/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 11 (C-5)
UNIT 11 Random Numbers.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Time Management.  Time management is concerned with OS facilities and services which measure real time.  These services include:  Keeping track of.
System calls for Process management Process creation, termination, waiting.
Advanced loop controls. Loop Controls Recall from last week loop controls Event-controlled loops using sentinels repeats until a control variable takes.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Week 9 - Wednesday.  What did we talk about last time?  structs.
Using Libraries The make utility UNIX System Calls Further Topics C Programming:Part 4.
Advanced Programming in the UNIX Environment Hop Lee.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Computer Science 516 Addressing Modes. Addressing modes are how our programs get to data Multiple addressing modes created for specific uses Function.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
CHAPTER 6. SYSTEM DATA FILES AND INFORMATION System Programming 本份投影片大量參考熊博安教授的系統程式投影片 羅習五 國立中正大學資訊工程學系
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo
Chapter 9: Value-Returning Functions
Performance Analysis Tools
Week 9 - Wednesday CS222.
Functions, Part 2 of 2 Topics Functions That Return a Value
CS1010 Programming Methodology
By: Syed Shahrukh Haider
閨怨 ~王昌齡 閨中少婦不知愁, 春日凝妝上翠樓; 忽見陌頭楊柳色, 悔教夫婿覓封侯。.
閨怨 ~王昌齡 閨中少婦不知愁, 春日凝妝上翠樓; 忽見陌頭楊柳色, 悔教夫婿覓封侯。.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Chapter 9 Times and Timers Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.

2 Introduction Operating systems use timers for such tasks as –Process scheduling –Timeouts for network protocols –Periodic updates of system statistics Applications access system time and timer functions to –Measure performance –Identify the time when events occur –Implement protocols –Control interaction with users

9.1a POSIX Time

4 time_t Type and the time() Function In POSIX, the Epoch is the start point for measuring time –It is defined as 00:00 (midnight) on January 1, 1970 The POSIX base standard supports only a time resolution of seconds It expresses time since the Epoch using a time_t type, which is usually a long integer A program can access the system time (expressed in seconds since the Epoch) by calling the time() function #include time_t time(time_t *timeLocation); If timeLocation is not NULL, the function also stores the time in the location pointed to by timeLocation If successful, time() returns the number of seconds; otherwise it returns –1 If time_t is implemented as a 32-bit long integer, the number will overflow in 2038 If time_t is implemented as an unsigned 32-bit long integer, the number will overflow in 2106, but this implementation would not allow the time() function to return –1 If time_ t is implemented as a 64-bit long integer, the overflow will not occur for another 292 billion years

5 difftime() Function The difftime() function computes the difference between two time values of type time_t #include double difftime(time_t timeA, time_t timeB); The timeB parameter is subtracted from the timeA parameter (i.e., A – B) The time resolution for time_t is one second, which may not be accurate enough for some calculations The program shown on the next two slides calculates the wall-clock (i.e., elapsed) time for a person to answer an addition problem

6 Example use of time() and difftime() #include #define MAX_NUMBER 100 // ******************************* int main(void) { time_t startTime; time_t stopTime; int valueX; int valueY; int guess; int answer; printf("\nAddition Drill Program \n\n"); srand(time(NULL)); valueX = rand() % MAX_NUMBER; valueY = rand() % MAX_NUMBER; answer = valueX + valueY; (More on next slide)

7 Example use of time() and difftime() (continued) printf(" %2d\n", valueX); printf(" + %2d\n", valueY); printf(" ----\n"); if (answer >= MAX_NUMBER) printf(" "); // Two spaces else printf(" "); // Three spaces startTime = time(NULL); scanf("%d", &guess); stopTime = time(NULL); if (guess == answer) printf("\nCorrect answer!\n"); else printf("\nWrong answer. The correct answer is %d\n", answer); printf("\nElapsed time: %.0f seconds\n", difftime(stopTime, startTime)); return 0; } // End main uxb2% a.out Addition Drill Program Correct answer! Elapsed time: 7 seconds uxb2% Sample Program Run

9.1b Date and Time

9 Displaying the Date and Time The localtime() function takes a parameter specifying the seconds since the Epoch and returns a pointer to a struct tm structure containing the components of time (such as day, month, and year) adjusted for local requirements The asctime() function converts the structure returned by localtime() to a 26-character English-language string Example: Mon Aug 21 10:00: \n\0 The ctime() function is equivalent to asctime(localtime(EpochTime)) #include struct tm *localtime(const time_t *EpochTime); char *asctime(const struct tm *timeRecordPtr); char *ctime(const time_t *EpochTime);

10 Example use of localtime(), asctime() and ctime() #include int main(void) { time_t currentTime; struct tm *localPtr; currentTime = time(NULL); localPtr = localtime(&currentTime); printf("Local time (using asctime): %s", asctime(localPtr)); printf("Local time (using ctime) : %s", ctime(&currentTime)); return 0; } // End main

11 struct tm Structure The struct tm structure has the members shown below int tm_sec;// Seconds after the minute [0, 60] int tm_min;// Minutes after the hour [0, 59] int tm_hour;// Hours since midnight [0, 23] int tm_mday;// Day of the month [1, 31] int tm_mon;// Months since January [0, 11] int tm_year;// Years since 1900 int tm_wday;// Days since Sunday [0, 6] int tm_yday;// Days since January 1 st [0, 365] int tm_isdst;// Flag indicating daylight savings time

12 Example use of struct tm Structure #include int main(void) { struct tm *localPtr; time_t currentTime; currentTime = time(NULL); localPtr = localtime(&currentTime); printf("Local time : %s\n", ctime(&currentTime)); printf("Seconds after minute: %d\n", localPtr->tm_sec); printf("Minutes after hour : %d\n", localPtr->tm_min); printf("Hours since midnight: %d\n", localPtr->tm_hour); printf("Day of the month : %d\n", localPtr->tm_mday); printf("Months since January: %d\n", localPtr->tm_mon); printf("Years since 1900 : %d\n", localPtr->tm_year); printf("Days since Sunday : %d\n", localPtr->tm_wday); printf("Days since Jan 1st : %d\n", localPtr->tm_yday); printf("DST Flag : %d\n", localPtr->tm_isdst); return 0; } // End main

13 Sample output for struct tm uxb2% a.out Local time : Wed Jul 26 19:36: Seconds after minute: 37 Minutes after hour : 36 Hours since midnight: 19 Day of the month : 26 Months since January: 6 Years since 1900 : 106 Days since Sunday : 3 Days since Jan 1st : 206 DST Flag : 1 uxb2%

14 gettimeofday() Function A time resolution of seconds is too coarse for timing programs or controlling program events The getttimeofday() function retrieves the system time in seconds and microseconds since the Epoch #include int gettimeofday(struct timeval *timePtr, void *); The struct timeval structure pointed to by timePtr receives the retrieved time The programmer should set the second parameter to NULL The function returns zero if successful; otherwise, some implementations return –1 and set errno The struct timeval structure contains two members time_t tv_sec; // Seconds since the Epoch time_t tv_usec; // Microseconds after the second

15 Example#1: use of gettimeofday() #include int main(void) { struct timeval timeRecord; int status; status = gettimeofday(&timeRecord, NULL); printf("Seconds since the Epoch : %d\n", timeRecord.tv_sec); printf("Microseconds after seconds: %d\n", timeRecord.tv_usec); return 0; } // End main uxb2% a.out Seconds since the Epoch : Microseconds after seconds: uxb2% Sample Program Run

16 Example#2: use of gettimeofday() #include #define MILLION L void functionToTime(void); int main(void) { struct timeval timeStart; struct timeval timeStop; long timeDifference; gettimeofday(&timeStart, NULL); functionToTime(); gettimeofday(&timeStop, NULL); timeDifference = MILLION * (timeStop.tv_sec - timeStart.tv_sec) + timeStop.tv_usec - timeStart.tv_usec; printf("The function took %ld microseconds\n", timeDifference); return 0; } // End main void functionToTime(void) { // Do some I/O or some calculations } // End functionToTime

9.2 Sleep Function

18 sleep() Function A process that voluntarily blocks for a specified time is said to sleep The sleep() function causes the calling thread to be suspended either until the specified number of seconds has elapsed or until the calling thread catches a signal #include unsigned int sleep(unsigned int seconds); In some implementations, the function returns 0 if the requested time has elapsed; otherwise, it returns the amount of unslept time if interrupted The function interacts with SIGALRM, so the programmer should avoid using them concurrently in the same process

19 Example use of sleep() #include int main(void) { int sleepTime; printf("\nPID: %d\n", getpid()); printf("\nHow long should I sleep (sec)? "); scanf("%d", &sleepTime); printf("\nGood night :)...\n"); sleep(sleepTime); printf("\nThat was a good rest!\n"); return 0; } // End main uxb2% a.out PID: How long should I sleep (sec)? 20 Good night :)... That was a good rest! uxb2% Sample Program Run