日志和时间函数设计

来源:互联网 发布:矩阵中diag什么意思 编辑:程序博客网 时间:2024/05/17 21:41

日志函数的需求:
a)输出错误日志,每天一个错误日志文件;
b)使用一些标准宏,准确定位错误位置和发生错误时间;
c)使用有格式的输出.

时间函数需求:
a)秒级second: time(NULL)
b)毫秒级ms:  GetTickCount (win32 api,返回当前时间的毫秒级,1tick=55us),常用于费时程序的统计,压缩一个文件.
c)微秒级us: gettimeofday返回的是一个时间结构struct tm
d)clock: 用来计算当前函数cpu调用的时间,如果是main函数里,则是整个程序的cpu调用时间了。clock/CLOCKS_PER_SEC那么返回的将是秒,否则返回微秒时间。
示例

1 LOG
int LOG(const char* lpszFormat,...)
{
 time_t now;
 struct tm *local;
 FILE* pLogFile;
 char fileName[MAX_DEPTH];

 time(&now);
 local = localtime(&now);
 //format file name
#ifdef ERROR
 sprintf(fileName,"%d-%02d-%02d.log",local->tm_year + 1900,/
   local->tm_mon + 1,local->tm_mday);
#else
 sprintf(fileName, "%s", "test.log");
#endif
 if (!(pLogFile = fopen(fileName,"a+"))) {
  return -1;
 }

 //record error time
 char strMsg[512];
 int strMsglen;
 //strMsglen = sprintf(strMsg,"%02d:%02d:%02d  ",local->tm_hour,local->tm_min,local->tm_sec);
 strMsglen = strftime(strMsg,sizeof(strMsg),"%H:%M:%S",local);

 va_list args;
 va_start(args,lpszFormat);
 fprintf(pLogFile,"[%s]",strMsg);
 vfprintf(pLogFile,lpszFormat,args);
 fprintf(pLogFile,"/n");
 fflush(pLogFile);
 va_end(args);

 fclose(pLogFile);
 return 0;
}

2 获取到当前时间的毫秒级,微秒级
//us指的微秒,microSecond, ms指的是毫秒,millonSecond
unsigned long long getUS();
unsigned long getMS();
unsigned long long getUS()
{
 struct timeval l_tv;
 gettimeofday(&l_tv,NULL);
 unsigned long long l_ret = 0;
 l_ret = (l_tv.tv_sec&0xFFFFFFFF)*1000000;
 l_ret += l_tv.tv_usec;
 return l_ret;
}

unsigned long getMS()
{
 struct timeval l_tv;
 gettimeofday(&l_tv,NULL);
 unsigned  long l_ret = 0;
 l_ret = (l_tv.tv_sec&0xFFFFFFFF)*1000;
 l_ret += (l_tv.tv_usec/1000);
 return l_ret;
}

3 clock --cpu time used
#include <stdio.h>
#include <time.h>

void elapsed_time(void);
void elapsed_time(void)
{
  long i, sum=0;
  for( i=0; i<1600000000ll; i++) sum+=i-299;
  printf("elapse time: %lu secs./n", clock()/CLOCKS_PER_SEC);
}

int main()
{
  elapsed_time();
  unsigned long long starts=clock();
  elapsed_time();
  printf("main time: %lu secs./n", clock()-starts );
  return 0;

原创粉丝点击