linux_c 網絡開發日記(3)時間編程

時間類型

 coordinated university time (UTC):世界標準時間,也就是大家所熟知的格林威治時間(GMT).
calender time:日曆時間,是從“一個標準時間點(1970年,1月1日零點)到此經歷的秒數“來表示時間。


時間獲取

#include<time>
time_t time(time_t *tloc)


功能:獲取日曆時間,即從1970/01/01/00時刻到現在所經歷的秒數。


時間轉換

struct tm *gmtime(const time_t *timep)
功能:將日曆時間轉換成格林威治時間,並保存在TM結構。
struct tm *localtime(const time_t *timep)
功能:將日曆時間轉換成本地時間,並保存在TM結構。


時間保存結構

struct tm {
int tm_sec;//秒
int tm_min;//分鐘值
int tm_hour小時制
int tm_mday;//本月第幾日
int tm_mon;;//本年第幾月
int tm_year;//tm_year+1900=哪一年
int tm_wday;//本週第幾日
int tm_yday;//本年第幾日
int tm_isdst;//日光節約時間
}


時間顯示

char *asctime(const struct tm *tm)
功能:將tm格式的時間轉化爲字符串,如:

 sat jul 30 08:43:03 2005


 char *ctime(const time_t *timep)
功能:將日曆時間轉化爲本地時間的字符串形式


獲取時間

int gettimeofday(struct timeval *tv,struct timezone *tz)
功能:獲取從今日凌晨到現在的時間差,常用於計算時間耗時。


struct timeval{
int tv_sec;//秒數
int tv_usec;//微妙數

}

下面這個小程序就是計算程序的運行時間。

#include<sys/time.h>
#include<stdio.h>
#include<stdlib.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++;
}

main()
{
	struct timeval tpstart, tpend;
	float timeuse;
	
	gettimeofday(&tpstart,NULL);//得到開始時間
	function();//運行function()
	gettimeofday(&tpend,NULL);//得到結束時間
/* 計算function的運行時間*/
	timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_usec-tpstart.tv_usec);
	timeuse/=1000000;
	printf("used time:%f\n", timeuse);
	exit(0);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章