(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"); //设置结束时间点 }