前言:Linux下的時間概念
這一章我們學習Linux的時間表示和計算函數
時間的表示
時間的測量
計時器的使用
1。時間表示 在程序當中,我們經常要輸出系統當前的時間,比如我們使用date命令
的輸出結果.這個時候我們可以使用下面兩個函數
- #include <time.h>
-
- time_t time(time_t *tloc);
- char *ctime(const time_t *clock);
time函數返回從1970年1月1日0點以來的秒數.存儲在time_t結構之中.不過這個函數的返
回值對于我們來說沒有什么實際意義.這個時候我們使用第二個函數將秒數轉化為字符串
.. 這個函數的返回類型是固定的:一個可能值為. Thu Dec 7 14:58:59 2000 這個字符串
的長度是固定的為26
2。時間的測量 有時候我們要計算程序執行的時間.比如我們要對算法進行時間分析
..這個時候可以使用下面這個函數.
- #include <sys/time.h>
-
- int gettimeofday(struct timeval *tv,struct timezone *tz);
- strut timeval {
- long tv_sec;
- long tv_usec;
- };
- gettimeofday將時間保存在結構tv之中.tz一般我們使用NULL來代替.
- [codes=c]
- #include <sys/time.h<
- #include <stdio.h<
- #include <math.h<
- void function()
- {
- unsigned int i,j;
- double y;
- for(i=0;i<1000;i++)
- for(j=0;j<1000;j++)
- y=sin((double)i);
- }
- main()
- {
- struct timeval tpstart,tpend;
- float timeuse;
- gettimeofday(&tpstart,NULL);
- function();
- gettimeofday(&tpend,NULL);
- timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+
- tpend.tv_usec-tpstart.tv_usec;
- timeuse/=1000000;
- printf("Used Time:%f\n",timeuse);
- exit(0);
- }
這個程序輸出函數的執行時間,我們可以使用這個來進行系統性能的測試,或者是函數算
法的效率分析.在我機器上的一個輸出結果是: Used Time:0.556070
3。計時器的使用 Linux操作系統為每一個進程提供了3個內部間隔計時器.
ITIMER_REAL:減少實際時間.到時的時候發出SIGALRM信號.
ITIMER_VIRTUAL:減少有效時間(進程執行的時間).產生SIGVTALRM信號.
ITIMER_PROF:減少進程的有效時間和系統時間(為進程調度用的時間).這個經常和上面一
個使用用來計算系統內核時間和用戶時間.產生SIGPROF信號.
具體的操作函數是:
- #include <sys/time.h>
- int getitimer(int which,struct itimerval *value);
- int setitimer(int which,struct itimerval *newval,
- struct itimerval *oldval);
- struct itimerval {
- struct timeval it_interval;
- struct timeval it_value;
- }
getitimer函數得到間隔計時器的時間值.保存在value中 setitimer函數設置間隔計時器
的時間值為newval.并將舊值保存在oldval中. which表示使用三個計時器中的哪一個.
itimerval結構中的it_value是減少的時間,當這個值為0的時候就發出相應的信號了. 然
后設置為it_interval值.
- #include <sys/time.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <signal.h>
- #include <string.h>
- #define PROMPT "時間已經過去了兩秒鐘\n\a"
- char *prompt=PROMPT;
- unsigned int len;
- void prompt_info(int signo)
- {
- write(STDERR_FILENO,prompt,len);
- }
- void init_sigaction(void)
- {
- struct sigaction act;
- act.sa_handler=prompt_info;
- act.sa_flags=0;
- sigemptyset(&act.sa_mask);
- sigaction(SIGPROF,&act,NULL);
- }
- void init_time()
- {
- struct itimerval value;
- value.it_value.tv_sec=2;
- value.it_value.tv_usec=0;
- value.it_interval=value.it_value;
- setitimer(ITIMER_PROF,&value,NULL);
- }
- int main()
- {
- len=strlen(prompt);
- init_sigaction();
- init_time();
- while(1);
- exit(0);
- }
這個程序每執行兩秒中之后會輸出一個提示.