Chinaunix首页 | 论坛 | 博客
  • 博客访问: 56756
  • 博文数量: 20
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 200
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-30 11:11
文章分类

全部博文(20)

文章存档

2018年(2)

2010年(2)

2009年(16)

我的朋友

分类:

2009-11-30 11:52:22

~\桌面\tt.c.html获得时间有以下两种方法
1、使用 time_t   *time(time_t   *)函数,它返回一个time_t指针,保存着从1970110点以来的秒数  
然后使用 char   *ctime(   const   time_t *)就可以得到类似date命令显示的日期格式字符串了。例子:  
//------------------------用time()的例子-----------------------
#include   
int main()  
{  
    time_t tmNow = 0;  
  
    time(&tmNow);//
    printf("%ld,%s", tmNow, ctime(&tmNow));  //打印如“Mon Sep  7 13:20:04 2009”信息
 
    exit(0);  
}  
//------------------------------------------------------------
2、调用gettimeofday将时间写入timeval结构中,这种方法精确到微妙
#include
int gettimeofday (struct timeval *__restrict __tv, __timezone_ptr_t __tz)
struct timeval
{
    __time_t tv_sec;            /* Seconds.  */
    long int tv_usec;           /* useconds.  */
};
其中  
tv_sec   保存着从1970110点以来的秒数  
tv_usec  保存微秒数  
这时也可以调用ctime函数将tv_sec的内容传入,同样可得到类dete命令显示的字符串  
一般timeval结构常用于计算进程运行的时间,主要是因为它的精度高。
还有一个更高精度的结构,这是linux最精确的时间结构
#include
struct timespec
{   time_t tv_sec;
    long int tv_nsec;  /*Nanoseconds*/
}
  
补充一点: time_t 在大多数系统中等于 long
//---------------------用timeval计算运行时间的例子-----------------------
#include
#include
#include
int isprime_num(int i);
int main()
{
        struct timeval t1;
        struct timeval t2;
        float elapse;
        int i;
        int count=0;
        //get the count prime number in 0..10000
        //start timing
        gettimeofday(&t1,NULL);

        for(i=0;i<=10000000;++i)
        {       if(isprime_num(i)==1)
                        count++;
        }
        //stop timing
        gettimeofday(&t2,NULL);
        elapse=1000000*(t2.tv_sec-t1.tv_sec)+t2.tv_usec-t1.tv_usec;
        elapse/=1000000;
        printf("the count of prime number is %d\n",count);
        printf("elapse time %f\n",(elapse));

        return 0;
}
//i是否素数
//出口:返回1表示是素数,0不是
int isprime_num(int i)
{
        int j;
        int top=(int)sqrt((float)i);
        for(j=2;j<=top;++j)
        {       if(i%j==0)
                        return 0;
        }
        return 1;
}
//-----------------------------------------------------------------

阅读(775) | 评论(0) | 转发(0) |
0

上一篇:linux thread

下一篇:Unicode、UCS和UTF介绍

给主人留下些什么吧!~~