?? linux下的時間概念 (zhuan).txt
字號:
作者:dio
email: hao@peng.com.cn
日期:8/20/2001 5:08:52 PM
這一章我們學習Linux的時間表示和計算函數(shù)
時間的表示
時間的測量
計時器的使用
1.時間表示 在程序當中,我們經(jīng)常要輸出系統(tǒng)當前的時間,比如我們使用date命令的輸出結果。這個時候我們可以使用下面兩個函數(shù)
#include
time_t time(time_t *tloc);
char *ctime(const time_t *clock);
time函數(shù)返回從1970年1月1日0點以來的秒數(shù)。存儲在time_t結構之中。不過這個函數(shù)的返回值對于我們來說沒有什么實際意義。這個時候我們使用第二個函數(shù)將秒數(shù)轉化為字符串。 這個函數(shù)的返回類型是固定的:一個可能值為。 Thu Dec 7 14:58:59 2000 這個字符串的長度是固定的為26
2.時間的測量 有時候我們要計算程序執(zhí)行的時間。比如我們要對算法進行時間分析。這個時候可以使用下面這個函數(shù)。
#include
int gettimeofday(struct timeval *tv,struct timezone *tz);
strut timeval {
long tv_sec; /* 秒數(shù) */
long tv_usec; /* 微秒數(shù) */
};
gettimeofday將時間保存在結構tv之中。tz一般我們使用NULL來代替。
#include
#include
#include
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:%fn",timeuse);
exit(0);
}
這個程序輸出函數(shù)的執(zhí)行時間,我們可以使用這個來進行系統(tǒng)性能的測試,或者是函數(shù)算法的效率分析。在我機器上的一個輸出結果是: Used Time:0.556070
3.計時器的使用 Linux操作系統(tǒng)為每一個進程提供了3個內部間隔計時器。
ITIMER_REAL:減少實際時間。到時的時候發(fā)出SIGALRM信號。
ITIMER_VIRTUAL:減少有效時間(進程執(zhí)行的時間)。產(chǎn)生SIGVTALRM信號。
ITIMER_PROF:減少進程的有效時間和系統(tǒng)時間(為進程調度用的時間)。這個經(jīng)常和上面一個使用用來計算系統(tǒng)內核時間和用戶時間。產(chǎn)生SIGPROF信號。
具體的操作函數(shù)是:
#include
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函數(shù)得到間隔計時器的時間值。保存在value中 setitimer函數(shù)設置間隔計時器的時間值為newval。并將舊值保存在oldval中。 which表示使用三個計時器中的哪一個。 itimerval結構中的it_value是減少的時間,當這個值為0的時候就發(fā)出相應的信號了。 然后設置為it_interval值。
#include
#include
#include
#include
#include
#define PROMPT "時間已經(jīng)過去了兩秒鐘na"
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);
}
這個程序每執(zhí)行兩秒中之后會輸出一個提示。
來源:中國計算機世界
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -