工具函数

1.时间处理函数

int64_t CycleClock_Now() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return static_cast<int64>(tv.tv_sec) * 1000000 + tv.tv_usec;
}

double WallTime_Now() {
    //return microseconds since the epoch(纪元)
    return CycleClock_Now() * 0.000001;
}

//将当前时间换算成
//tm_sec
//tm_min
//tm_mday
//tm_mon
//tm_year
//tm_wday
//tm_yday
//tm_isdst
//tm_gmtoff
//tm_zone
localtime_r(&data_->timestamp_, &data_->tm_time_); 

//获取微秒数
int usecs = static_case<int>((now-data_->timestamp_)*1000000);
View Code

2. backtrace函数调用

int GetStackTrace(void** result, int max_depth, int skip_count) {
static const int kStackLength = 64;
void * stack[kStackLength];
int size;

size = backtrace(stack, kStackLength);
skip_count++;  // we want to skip the current frame as well
int result_count = size - skip_count;
if (result_count < 0)
    result_count = 0;
    if (result_count > max_depth)
    result_count = max_depth;
    for (int i = 0; i < result_count; i++)
     result[i] = stack[i + skip_count];
 
  return result_count;
}
View Code

 3. wordsize

#if defined __x86_64__
#define __WORDSIZE  64
#define __WORDSIZE_COMPAT32 1
#else
#define __WORDSIZE 32
#endif
//在不同的内核(x86_64/i386)这已经初始化好了,直接用
View Code

4. 异步安全的assert

//glog-0.3.3: 60
// We don't use assert() since it's not guaranteed to be
// async-signal-safe.  Instead we define a minimal assertion
 // macro. So far, we don't need pretty printing for __FILE__, etc.

// A wrapper for abort() to make it callable in ? :.
 static int AssertFail() {
   abort();
   return 0;  // Should not reach.
}
 
 #define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail())
View Code

5.C++大小端的判断方法

在/usr/include/下有一个endian.h,有很多宏用来判断这些,BYTE_ORDER == __BIG_ENDIAN
View Code
原文地址:https://www.cnblogs.com/457220157-FTD/p/4129203.html