日誌和時間函數設計

來源:互聯網
上載者:User

日誌函數的需求:
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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.