c语言计时器

(1)my_time.h

#ifndef MY_TIME_H_
#define  MY_TIME_H_

typedef struct time_manager_t time_manager_t;
struct time_manager_t
{
                 void (*set_clock)(time_manager_t *this);
	 void (*cal_clock)(time_manager_t *this,char *where);	
	 void (*destroy)(time_manager_t *this);
};
time_manager_t *create_time_manager();

#endif

 

 

(2)my_time.c

 

#include "my_time.h"
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <malloc.h>
#include <sys/time.h>
//设置时间打印到的文件
#define MY_TIME_PATH "/root/time.txt"
typedef struct private_time_manager_t private_time_manager_t;

struct private_time_manager_t
{
          time_manager_t public;
	   FILE *file;
	   struct timeval start;
	   struct timeval end;
};

void  set_clock(private_time_manager_t *this)
{
         gettimeofday(&this->start,NULL);
}

void  cal_clock(private_time_manager_t *this,char *where)
{
         double timeuse;
         gettimeofday(&this->end,NULL);
	  //计算相隔时间,多减去3微妙,由于测试3微妙微计算的时间
	  timeuse = 1000000 * (this->end.tv_sec-this-> start.tv_sec ) + this->end.tv_usec-this->start.tv_usec-3;
         timeuse /= 1000000;
         fprintf(this->file,"%s:%f\n",where,timeuse);
}

void  destroy(private_time_manager_t *this)
{
        fclose(this->file);
	 free(this);
}

time_manager_t *create_time_manager()
{
	private_time_manager_t *this=(private_time_manager_t *)malloc(sizeof(private_time_manager_t));
       this->file=fopen(MY_TIME_PATH,"a+");
	if(this->file==NULL)
	{
	         printf("file open fail\n");
	         return NULL;
	}

	this->public.set_clock=(void (*)(time_manager_t *))set_clock;
	this->public.cal_clock=(void (*)(time_manager_t *,char *))cal_clock;	
	this->public.destroy=(void (*)(time_manager_t *))destroy;
	return &this->public;
}


void main()
{
        time_manager_t *this=create_time_manager();
        this->set_clock(this);  //设置开始时间点
     this->cal_clock(this,"a"); //设置结束时间点
}

 

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值