您的位置:首页 > 运维架构 > Linux

LINUX C系统编程学习笔记-----------时间编程

2012-06-26 10:51 330 查看
时间编程
格林威治时间(GMT )是世界标准时间(UTC)。

需要头文件 sys/time.h

相关函数:

time_t time(time_t *tloc);

作用:获取日历时间,即从1970年1月1日0点到现在所经历的秒数。

struct tm * gmtime (const time_t *timep);

作用:将日历时间转化为格林威治时间,并保存至 TM 结构中 。

struct tm * localtime(const time_t * timep);

作用:将日历时间转化为本地时间并保存至 TM 结构中。

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; //日光节约时间----这个东西我也不懂,至少现在的我还用不到它
}

注意上面不是完整的 TM 结构。

时间显示

char * asctime(const struct tm *tm);

将tm格式的时间转化为字符串形式,如:sat jul 30 08:43:03 2012

char * ctime(const time_t *timep);

将日历时间转化为本地时间的字符串形式。

例:

#include <stdio.h> #include <stdlib.h>
#include <time.h>

int main(void)
{
time_t tl;
struct tm * te;

tl = time(NULL);
te = localtime(&tl);
printf("NOW!Date is %s",asctime(te));

return 0;

}

获取时间

int gettimeofday(struct tomrval *tv,struct timezone *tz);

获取从今日凌晨到现在的时间差,常用于计算时间耗时。

timeval结构:

struct timeval
{
int tv_sec; //秒数
int tv_usec; //微秒数};

例:

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <math.h>
//算法分析
void function()
{
unsigned int i,j;
double y;
for (i = 0; i < 1000; i++)
{
for (j = 0; i < 1000; i++)
{
y++;
}
}
}
int main(void)
{
struct timeval tpstart,tpend;
float timeuse;
gettimeofday(&tpstart,NULL);//开始时间
function();
gettimeofday(&tpend,NULL);//结束时间
//计算执行时间
timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpsart.tv_usec;
timeuse /= 1000000;
printf("Used Time: %f\n",timeuse);
exit(0);}

以上代码是测试function函数的耗时。

延时执行

unsigned int sleep(unsignde int seconds);

使程序睡眠seconds秒

void usleep(unsigned long usec);

使程序睡眠usec微秒

关于文件编程的补充 :

1.路径获取

char *getcwd (char *buffer,size_t size);

提供一个size大小的buffer,getcwd会把当前路径名copy到buffer 中,如果buffer太小,函数会返回-1.

例:

#include <unistd.h>
#include <stdio.h>
int main(void)
{
char buf[80];
getcwd(buf,sizeof(buf));
printf("current working direntory: %s\n",buf); return 0;

}

2.创建目录

#include <sys/stat.h>

int mkdir(char *dir,int mode);

创建一个新目录,返回值:0表示成功,-1表示出错。

文章中的代码由于很少,所以基本上没用注释,我相信应该不会很难看懂吧。

小子是自学这些东西,拿来与和我一样菜的人一起分享一下,想去年,学完C语言,都不知道能干什么,更不相信C语言居然还能变出软件来,想去网上找些代码来看吧,可是没有一个能看懂的。说真的,当时真是很受打击。现在稍微摸到点门路,还在路上摸索着,也希望我的一些文章能稍微帮助和我一样的人,能给自己一个继续坚持下去的动力。文章中虽然,好多东西都涉及不到,但是,我感觉这些还蛮好掌握的,所以我们可以慢慢来·····一点点进步,一点点深入·······

欢迎各位大神指点批评········
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: