C++应用开发小技巧总结之计算时间间隔、获取系统时间戳、互斥锁使用

C++应用开发小技巧总结:

1. 计算时间间隔

  • std::chrono::steady_clock 专门设计用来计算时间间隔(基于C++11)
  • 应用示例:
#include 
#include 

int main(int argc ,char** argv) {
    int TIMES = 1000000000;
    int value = 0;
    
    auto start = std::chrono::steady_clock::now();
    
    for (int i = 0; i < TIMES; ++i) {
        value = 1 - value;
    }
    
    auto end = std::chrono::steady_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " ms." << std::endl;
    
    return 0;
}

  • 参考资料:
    • http://www.cplusplus.com/reference/chrono/steady_clock/
    • http://www.cplusplus.com/reference/chrono/high_resolution_clock/
    • http://www.cplusplus.com/reference/chrono/system_clock/
    • 关于 system_clock、steady_clock、high_resolution_clock 的具体说明及区别: https://stackoverflow.com/questions/13263277/difference-between-stdsystem-clock-and-stdsteady-clock

2. 获取系统时间戳

  • C++11 提供了chrono,专门用来处理时间相关的业务逻辑,它是一个处于std下的子命名空间,详细内容可以参考 std::chrono,下面介绍两种应用场景.

2.1. 获取当前时间戳

// get current local time stamp, unit is ms(milliseconds)
int64_t GetCurrentLocalTimeStamp() {
    std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp = 
        std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
    auto tmp = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
    return tmp.count(); 
    // return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count();
}
  • system_clock是系统级时钟,能够获取当前的time_point,其now静态成员函数用来获取当前时间.
  • time_point的time_since_epoch成员方法获取1970以来的时间,然后通过time_point_cast或者duration_cast的count函数获取具体时间.

2.2. 获取时间跨度

int CountTimeConsume() {
    std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();

    std::cout << "printing out 1000 stars...\n";
    for (int i = 0; i < 1000; ++i)
        std::cout << "*";
    std::cout << std::endl;

    std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();

    std::chrono::duration<double, std::milli> time_span = t2 - t1;

    std::cout << "It took me " << time_span.count() << " milliseconds.";
    std::cout << std::endl;

    return 0;
}

3. C++11互斥锁使用

  • std::lock_guard 上锁解锁更高效,不易造成死锁
// 伪代码
#include 
#include 

std::mutex mutex_lock;
bool kSharedResource;

void Thread1() {
  {
    std::lock_guard<std::mutex> lg(mutex_lock);
    kSharedResource = true;
  }
}

void Thread2() {
  {
    std::lock_guard<std::mutex> lg(mutex_lock);
    kSharedResource = false;
  }
}

int main(int argc, char** argv) {
  auto thread_handle = new std::Thread(Thread1);
  
  while(1) {
    Thread2();
  }

  thread_handle->join();

  return 0
}

你可能感兴趣的:(C/C++,c++,开发语言,c语言)