SlideShare a Scribd company logo
1 of 29
Download to read offline
Timers
Time is kept relative to a particular point in time:
Jan 1, 1970 GMT
Two kernel counters: one for the seconds since
Jan 1, 1970 and one for the microseconds since
Jan 1, 1970
Code
#include <sys/time.h>
structu timeval theTime;
gettimeofday(&theTime, NULL);
struct timeval { long tv_sec; long tv_usec;}
System code
You can read the system code in kernel/time.c
(if you are looking at linux, you'll realy need to
look in the appropriate arch directory.)
For tv_usec to correct, it needs to be
incremented once every microsecond. The
system can track the passage of time by
counting the number of interrupts that have
occurred since system boot.
time of day clock
i386 has a time of day clock (this may run
continuously or may be set at system boot
time). Although it may not have the accuracy
desired, it can be used as the base for
incrementing the 10-millisecond clock.
10 millisecond clock
The hardware has a programmable time that
can be set to issue an interrupt every k time
units: in Linux this is set to 10 milliseconds.
So the gettimeofday function determines how
many microseconds and seconds have passed
since the time of day clock.
when is the system clock updated?
Updating the system clock
the interrupt service routine for the clock
(timer_interrupt) calls the do_timer function in
kernel/sched.c (scheduler related functions).
This increment the jiffies counter each time it
runs and marks a counter (TIMER_BH) for
execution in the ret_from_sys_call . For an
overview of the sequence of events in the case
of an interrupt see p 26 (Sec 4.1.1)
Task Control
ret_from_sys_call
this is a standard set of tasks to complete
(dispatch) any accumulated system work:
−   pending signals
−   pending interrupt tasks
−   schedule other tasks
slow vs fast: fast interrupts don't do much work,
so interrupts are disabled. That means no
further work will need to be done.
slow
slow interrupts have more to do. So the ISR is
divided into two pieces: the “upper” half that is
“fast”, so interrupts can be disabled, and the
“lower” half, which is “slow”, but the tasks do not
require non-interruptable status.
These defered tasks can be scheduled later.
Since the kernel is really “multi-threaded”, more
than one ISR may have run with postponed
bottom half events: these are all handled when
the bottom half is scheduled.
timer bottom half
time bottom half activities:
−   system timer updates
−   per process time updates
−   stores the value in the struct timeval
Per process timers
kernel needs to maintain time spent by each
process
timer info saved in the process's descriptor
when a new task is created, the kernel create's
a new task_struct
the task_struct contains all the process specific
info, some of which is time info:
struct task_struct {
...
long counter;
...
unsigned long polkicy, rt_priority;
unsigned long it_real_value, it_prof_value, it_virt_value;
unsigned long it_real_incr, it_prof_incr, it_virt_incr;
struct time_list real_timer;
// contains tms_utime, tms_stime. tmx_cstime

struct tms;
unsigned long start_time;
long per_cpu_utime[NR_CPUS], per_cpu_stime[], cutime, cstime;
...
}
// in timer.c (bottom half processing)

/*
 * Called from the timer interrupt handler to charge one tick to the current
 * process. user_tick is 1 if the tick is user time, 0 for system.
 */
void update_process_times(int user_tick)
{
    struct task_struct *p = current;
    int cpu = smp_processor_id(), system = user_tick ^ 1;

    update_one_process(p, user_tick, system, cpu);
    run_local_timers();
    scheduler_tick(user_tick, system);
}
static inline void do_it_prof(struct task_struct *p)
{
   unsigned long it_prof = p->it_prof_value;

    if (it_prof) {
        if (--it_prof == 0) {
            it_prof = p->it_prof_incr;
            send_sig(SIGPROF, p, 1);
        }
        p->it_prof_value = it_prof;
    }
}
static inline void do_it_virt(struct task_struct * p, unsigned long ticks)
{
   unsigned long it_virt = p->it_virt_value;

    if (it_virt) {
        it_virt -= ticks;
        if (!it_virt) {
            it_virt = p->it_virt_incr;
            send_sig(SIGVTALRM, p, 1);
        }
        p->it_virt_value = it_virt;
    }
}
static inline void do_process_times(struct task_struct *p,
   unsigned long user, unsigned long system)
{
   unsigned long psecs;

    psecs = (p->utime += user);
    psecs += (p->stime += system);
    if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_cur) {
        /* Send SIGXCPU every second.. */
        if (!(psecs % HZ))
            send_sig(SIGXCPU, p, 1);
        /* and SIGKILL when we go over max.. */
        if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_max)
            send_sig(SIGKILL, p, 1);
    }
}
void update_one_process(struct task_struct *p, unsigned long user,
       unsigned long system, int cpu)
{
  do_process_times(p, user, system);
  do_it_virt(p, user);
  do_it_prof(p);
}
itimers
the itimers use kernel time to keep track of
−   itimer real: passage of real time
−   itimer virtual: passage of virtual time (only when the
    process is running)
−   itimer prof: time the the process is actually running
    and the time that the kernel is doing work on the
    process's behalf
(countdown timers)
Initializing timers
setitimer (do a man)
int getitimer(int which, struct itimerval *value);
int setitimer(int which, const struct itimerval *value, struct itimer-
     val *ovalue);

The system provides each process with three interval timers, each
decrementing in a distinct time domain. When any timer expires, a sig-
nal is sent to the process, and the timer (potentially) restarts.

ITIMER_REAL decrements in real time, and delivers SIGALRM upon expi-
       ration.

ITIMER_VIRTUAL decrements only when the process is executing, and
       delivers SIGVTALRM upon expiration.

ITIMER_PROF decrements both when the process executes and when the
       system is executing on behalf of the process. Coupled
       with ITIMER_VIRTUAL, this timer is usually used to pro-
       file the time spent by the application in user and ker-
       nel space. SIGPROF is delivered upon expiration.
Timer values are defined by the following structures:

   struct itimerval {
      struct timeval it_interval; /* next value */
      struct timeval it_value; /* current value */
   };
   struct timeval {
      long tv_sec;            /* seconds */
      long tv_usec;            /* microseconds */
   };
itimers
two values:
−   current value
−   interval: value to initialize the counter: it's a
    countdown)
getitimer
getitimer reads the value of a timer
#include <sys/time.h>

struct itimerval v;

v.it_interval.tv_sec = 9;
v.it_interval.tv_usec = 999999;

v.it_value.tv_sec = 9
v.it_value.tv_usec = 999999;

setitimer(ITIMER_REAL, &v, NULL);

getitimer(ITIMER_REAL, &v);

printf(quot;... %ld seconds, $ld microseconds ...quot;,
 ..., v.it_value.tv_sec, v.it_value.tv_usec, ...);
...
Signals
A signal will be sent when a timer “runs out”. In
order to make use of this, you need to set your
own signal handler.
this means that you define a function that will be
scheduled (invoked) when the signal is
received.
It's the user version of an ISR.
How to add a handler


 signal(SIGALRM, p_realt_handler);
 signal(SIGVTALRM, p_virtt_handler);
 signal(SIGPROF, p_proft_handler);
which signals?
a signal can be sent from one process to
another
do a man 7 signal to see all the signals
You can use a signal for arbitrary events
(though there are better ways to indicate an
event and coordinate actions among processes)
Specific SIGALRM: SIGPROF, SIGVTALRM,
SIGALRM
my sigA
check sigA.c for an example of setting a handler
(his version has a “race” condition.
doing Part A
Your part A should just set a real itimer to raise
a signal once every second.
You should define a handler that increments a
counter each time it is interrupted.
You can integrate this with your shell so that
you can do a variety of actions and then check
how much time you've used. (*You don't need
to convert to actual time of day.)

More Related Content

What's hot

Operating System 5
Operating System 5Operating System 5
Operating System 5tech2click
 
Bootloader and MMU (english)
Bootloader and MMU (english)Bootloader and MMU (english)
Bootloader and MMU (english)Sneeker Yeh
 
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...David Evans
 
Transactional Memory
Transactional MemoryTransactional Memory
Transactional MemoryYuuki Takano
 
Unit iios process scheduling and synchronization
Unit iios process scheduling and synchronizationUnit iios process scheduling and synchronization
Unit iios process scheduling and synchronizationdonny101
 
OS - CPU Scheduling
OS - CPU SchedulingOS - CPU Scheduling
OS - CPU Schedulingvinay arora
 
Core Scheduling for Virtualization: Where are We? (If we Want it!)
Core Scheduling for Virtualization: Where are We? (If we Want it!)Core Scheduling for Virtualization: Where are We? (If we Want it!)
Core Scheduling for Virtualization: Where are We? (If we Want it!)Dario Faggioli
 
Round robin scheduling
Round robin schedulingRound robin scheduling
Round robin schedulingRaghav S
 
cpu sechduling
cpu sechduling cpu sechduling
cpu sechduling gopi7
 
Distributed computing time
Distributed computing timeDistributed computing time
Distributed computing timeDeepak John
 
CPU Scheduling algorithms
CPU Scheduling algorithmsCPU Scheduling algorithms
CPU Scheduling algorithmsShanu Kumar
 
CPU Scheduling Algorithms
CPU Scheduling AlgorithmsCPU Scheduling Algorithms
CPU Scheduling AlgorithmsTayba Farooqui
 
Comparison Analysis of CPU Scheduling : FCFS, SJF and Round Robin
Comparison Analysis of CPU Scheduling : FCFS, SJF and Round RobinComparison Analysis of CPU Scheduling : FCFS, SJF and Round Robin
Comparison Analysis of CPU Scheduling : FCFS, SJF and Round RobinUniversitas Pembangunan Panca Budi
 
Comparision of scheduling algorithms
Comparision of scheduling algorithmsComparision of scheduling algorithms
Comparision of scheduling algorithmsTanya Makkar
 

What's hot (20)

Operating System 5
Operating System 5Operating System 5
Operating System 5
 
Bootloader and MMU (english)
Bootloader and MMU (english)Bootloader and MMU (english)
Bootloader and MMU (english)
 
Os4
Os4Os4
Os4
 
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...
 
OSCh7
OSCh7OSCh7
OSCh7
 
Transactional Memory
Transactional MemoryTransactional Memory
Transactional Memory
 
Unit iios process scheduling and synchronization
Unit iios process scheduling and synchronizationUnit iios process scheduling and synchronization
Unit iios process scheduling and synchronization
 
OS - CPU Scheduling
OS - CPU SchedulingOS - CPU Scheduling
OS - CPU Scheduling
 
Ch05
Ch05Ch05
Ch05
 
Core Scheduling for Virtualization: Where are We? (If we Want it!)
Core Scheduling for Virtualization: Where are We? (If we Want it!)Core Scheduling for Virtualization: Where are We? (If we Want it!)
Core Scheduling for Virtualization: Where are We? (If we Want it!)
 
Cpu Scheduling Galvin
Cpu Scheduling GalvinCpu Scheduling Galvin
Cpu Scheduling Galvin
 
Round robin scheduling
Round robin schedulingRound robin scheduling
Round robin scheduling
 
cpu sechduling
cpu sechduling cpu sechduling
cpu sechduling
 
Distributed computing time
Distributed computing timeDistributed computing time
Distributed computing time
 
CPU Scheduling algorithms
CPU Scheduling algorithmsCPU Scheduling algorithms
CPU Scheduling algorithms
 
CPU Scheduling Algorithms
CPU Scheduling AlgorithmsCPU Scheduling Algorithms
CPU Scheduling Algorithms
 
Os module 2 ba
Os module 2 baOs module 2 ba
Os module 2 ba
 
Comparison Analysis of CPU Scheduling : FCFS, SJF and Round Robin
Comparison Analysis of CPU Scheduling : FCFS, SJF and Round RobinComparison Analysis of CPU Scheduling : FCFS, SJF and Round Robin
Comparison Analysis of CPU Scheduling : FCFS, SJF and Round Robin
 
Comparision of scheduling algorithms
Comparision of scheduling algorithmsComparision of scheduling algorithms
Comparision of scheduling algorithms
 
Transactional Memory
Transactional MemoryTransactional Memory
Transactional Memory
 

Similar to Timers in Unix/Linux

Concurrency 2010
Concurrency 2010Concurrency 2010
Concurrency 2010敬倫 林
 
class12_time.ppt
class12_time.pptclass12_time.ppt
class12_time.pptGauravWaila
 
Week 1 Time_measuremenjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjt.pdf
Week 1 Time_measuremenjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjt.pdfWeek 1 Time_measuremenjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjt.pdf
Week 1 Time_measuremenjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjt.pdfdevinezekiel2003
 
Priority Scheduling.pptx
Priority Scheduling.pptxPriority Scheduling.pptx
Priority Scheduling.pptxSarupyaDatta1
 
RTOS implementation
RTOS implementationRTOS implementation
RTOS implementationRajan Kumar
 
Process scheduling
Process schedulingProcess scheduling
Process schedulingHao-Ran Liu
 
Linux Timer device driver
Linux Timer device driverLinux Timer device driver
Linux Timer device driver艾鍗科技
 
How to Create a Countdown Timer in Python.pdf
How to Create a Countdown Timer in Python.pdfHow to Create a Countdown Timer in Python.pdf
How to Create a Countdown Timer in Python.pdfabhishekdf3
 
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)Simen Li
 
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxInstruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxcarliotwaycave
 
Help Needed!UNIX Shell and History Feature This project consists.pdf
Help Needed!UNIX Shell and History Feature This project consists.pdfHelp Needed!UNIX Shell and History Feature This project consists.pdf
Help Needed!UNIX Shell and History Feature This project consists.pdfmohdjakirfb
 
Router Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditionsRouter Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditionsMorteza Mahdilar
 
C++ C++ C++ In Chapter 1- the class clockType was designed to implem.docx
C++ C++ C++   In Chapter 1- the class clockType was designed to implem.docxC++ C++ C++   In Chapter 1- the class clockType was designed to implem.docx
C++ C++ C++ In Chapter 1- the class clockType was designed to implem.docxCharlesCSZWhitei
 

Similar to Timers in Unix/Linux (20)

timers 2.ppt
timers 2.ppttimers 2.ppt
timers 2.ppt
 
Unix presentation.pdf
Unix presentation.pdfUnix presentation.pdf
Unix presentation.pdf
 
Timer
TimerTimer
Timer
 
Concurrency 2010
Concurrency 2010Concurrency 2010
Concurrency 2010
 
class12_time.ppt
class12_time.pptclass12_time.ppt
class12_time.ppt
 
Week 1 Time_measuremenjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjt.pdf
Week 1 Time_measuremenjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjt.pdfWeek 1 Time_measuremenjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjt.pdf
Week 1 Time_measuremenjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjt.pdf
 
Priority Scheduling.pptx
Priority Scheduling.pptxPriority Scheduling.pptx
Priority Scheduling.pptx
 
RTOS implementation
RTOS implementationRTOS implementation
RTOS implementation
 
Process scheduling
Process schedulingProcess scheduling
Process scheduling
 
Sysprog 12
Sysprog 12Sysprog 12
Sysprog 12
 
Sysprog 12
Sysprog 12Sysprog 12
Sysprog 12
 
Linux Timer device driver
Linux Timer device driverLinux Timer device driver
Linux Timer device driver
 
I os 06
I os 06I os 06
I os 06
 
How to Create a Countdown Timer in Python.pdf
How to Create a Countdown Timer in Python.pdfHow to Create a Countdown Timer in Python.pdf
How to Create a Countdown Timer in Python.pdf
 
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
 
Microkernel Development
Microkernel DevelopmentMicrokernel Development
Microkernel Development
 
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxInstruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
 
Help Needed!UNIX Shell and History Feature This project consists.pdf
Help Needed!UNIX Shell and History Feature This project consists.pdfHelp Needed!UNIX Shell and History Feature This project consists.pdf
Help Needed!UNIX Shell and History Feature This project consists.pdf
 
Router Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditionsRouter Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditions
 
C++ C++ C++ In Chapter 1- the class clockType was designed to implem.docx
C++ C++ C++   In Chapter 1- the class clockType was designed to implem.docxC++ C++ C++   In Chapter 1- the class clockType was designed to implem.docx
C++ C++ C++ In Chapter 1- the class clockType was designed to implem.docx
 

Recently uploaded

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

Timers in Unix/Linux

  • 1. Timers Time is kept relative to a particular point in time: Jan 1, 1970 GMT Two kernel counters: one for the seconds since Jan 1, 1970 and one for the microseconds since Jan 1, 1970
  • 2. Code #include <sys/time.h> structu timeval theTime; gettimeofday(&theTime, NULL); struct timeval { long tv_sec; long tv_usec;}
  • 3. System code You can read the system code in kernel/time.c (if you are looking at linux, you'll realy need to look in the appropriate arch directory.) For tv_usec to correct, it needs to be incremented once every microsecond. The system can track the passage of time by counting the number of interrupts that have occurred since system boot.
  • 4. time of day clock i386 has a time of day clock (this may run continuously or may be set at system boot time). Although it may not have the accuracy desired, it can be used as the base for incrementing the 10-millisecond clock.
  • 5. 10 millisecond clock The hardware has a programmable time that can be set to issue an interrupt every k time units: in Linux this is set to 10 milliseconds. So the gettimeofday function determines how many microseconds and seconds have passed since the time of day clock. when is the system clock updated?
  • 6. Updating the system clock the interrupt service routine for the clock (timer_interrupt) calls the do_timer function in kernel/sched.c (scheduler related functions). This increment the jiffies counter each time it runs and marks a counter (TIMER_BH) for execution in the ret_from_sys_call . For an overview of the sequence of events in the case of an interrupt see p 26 (Sec 4.1.1)
  • 8. ret_from_sys_call this is a standard set of tasks to complete (dispatch) any accumulated system work: − pending signals − pending interrupt tasks − schedule other tasks slow vs fast: fast interrupts don't do much work, so interrupts are disabled. That means no further work will need to be done.
  • 9. slow slow interrupts have more to do. So the ISR is divided into two pieces: the “upper” half that is “fast”, so interrupts can be disabled, and the “lower” half, which is “slow”, but the tasks do not require non-interruptable status. These defered tasks can be scheduled later. Since the kernel is really “multi-threaded”, more than one ISR may have run with postponed bottom half events: these are all handled when the bottom half is scheduled.
  • 10. timer bottom half time bottom half activities: − system timer updates − per process time updates − stores the value in the struct timeval
  • 11. Per process timers kernel needs to maintain time spent by each process timer info saved in the process's descriptor when a new task is created, the kernel create's a new task_struct the task_struct contains all the process specific info, some of which is time info:
  • 12. struct task_struct { ... long counter; ... unsigned long polkicy, rt_priority; unsigned long it_real_value, it_prof_value, it_virt_value; unsigned long it_real_incr, it_prof_incr, it_virt_incr; struct time_list real_timer; // contains tms_utime, tms_stime. tmx_cstime struct tms; unsigned long start_time; long per_cpu_utime[NR_CPUS], per_cpu_stime[], cutime, cstime; ... }
  • 13. // in timer.c (bottom half processing) /* * Called from the timer interrupt handler to charge one tick to the current * process. user_tick is 1 if the tick is user time, 0 for system. */ void update_process_times(int user_tick) { struct task_struct *p = current; int cpu = smp_processor_id(), system = user_tick ^ 1; update_one_process(p, user_tick, system, cpu); run_local_timers(); scheduler_tick(user_tick, system); }
  • 14. static inline void do_it_prof(struct task_struct *p) { unsigned long it_prof = p->it_prof_value; if (it_prof) { if (--it_prof == 0) { it_prof = p->it_prof_incr; send_sig(SIGPROF, p, 1); } p->it_prof_value = it_prof; } }
  • 15. static inline void do_it_virt(struct task_struct * p, unsigned long ticks) { unsigned long it_virt = p->it_virt_value; if (it_virt) { it_virt -= ticks; if (!it_virt) { it_virt = p->it_virt_incr; send_sig(SIGVTALRM, p, 1); } p->it_virt_value = it_virt; } }
  • 16. static inline void do_process_times(struct task_struct *p, unsigned long user, unsigned long system) { unsigned long psecs; psecs = (p->utime += user); psecs += (p->stime += system); if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_cur) { /* Send SIGXCPU every second.. */ if (!(psecs % HZ)) send_sig(SIGXCPU, p, 1); /* and SIGKILL when we go over max.. */ if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_max) send_sig(SIGKILL, p, 1); } }
  • 17. void update_one_process(struct task_struct *p, unsigned long user, unsigned long system, int cpu) { do_process_times(p, user, system); do_it_virt(p, user); do_it_prof(p); }
  • 18. itimers the itimers use kernel time to keep track of − itimer real: passage of real time − itimer virtual: passage of virtual time (only when the process is running) − itimer prof: time the the process is actually running and the time that the kernel is doing work on the process's behalf (countdown timers)
  • 20. int getitimer(int which, struct itimerval *value); int setitimer(int which, const struct itimerval *value, struct itimer- val *ovalue); The system provides each process with three interval timers, each decrementing in a distinct time domain. When any timer expires, a sig- nal is sent to the process, and the timer (potentially) restarts. ITIMER_REAL decrements in real time, and delivers SIGALRM upon expi- ration. ITIMER_VIRTUAL decrements only when the process is executing, and delivers SIGVTALRM upon expiration. ITIMER_PROF decrements both when the process executes and when the system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, this timer is usually used to pro- file the time spent by the application in user and ker- nel space. SIGPROF is delivered upon expiration.
  • 21. Timer values are defined by the following structures: struct itimerval { struct timeval it_interval; /* next value */ struct timeval it_value; /* current value */ }; struct timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ };
  • 22. itimers two values: − current value − interval: value to initialize the counter: it's a countdown)
  • 23. getitimer getitimer reads the value of a timer
  • 24. #include <sys/time.h> struct itimerval v; v.it_interval.tv_sec = 9; v.it_interval.tv_usec = 999999; v.it_value.tv_sec = 9 v.it_value.tv_usec = 999999; setitimer(ITIMER_REAL, &v, NULL); getitimer(ITIMER_REAL, &v); printf(quot;... %ld seconds, $ld microseconds ...quot;, ..., v.it_value.tv_sec, v.it_value.tv_usec, ...); ...
  • 25. Signals A signal will be sent when a timer “runs out”. In order to make use of this, you need to set your own signal handler. this means that you define a function that will be scheduled (invoked) when the signal is received. It's the user version of an ISR.
  • 26. How to add a handler signal(SIGALRM, p_realt_handler); signal(SIGVTALRM, p_virtt_handler); signal(SIGPROF, p_proft_handler);
  • 27. which signals? a signal can be sent from one process to another do a man 7 signal to see all the signals You can use a signal for arbitrary events (though there are better ways to indicate an event and coordinate actions among processes) Specific SIGALRM: SIGPROF, SIGVTALRM, SIGALRM
  • 28. my sigA check sigA.c for an example of setting a handler (his version has a “race” condition.
  • 29. doing Part A Your part A should just set a real itimer to raise a signal once every second. You should define a handler that increments a counter each time it is interrupted. You can integrate this with your shell so that you can do a variety of actions and then check how much time you've used. (*You don't need to convert to actual time of day.)