Computer >> Máy Tính >  >> Lập trình >> C ++

Làm cách nào để tạo bộ đếm thời gian bằng C ++ 11?

Ở đây chúng ta sẽ xem cách tạo bộ đếm thời gian bằng C ++. Ở đây chúng tôi đang tạo một lớp được gọi sau này. Lớp này có các thuộc tính sau.

  • int (mili giây để đợi cho đến khi chạy mã)
  • bool (Nếu điều này là đúng, nó sẽ trả về ngay lập tức và chạy mã sau thời gian được chỉ định trên một chuỗi khác)
  • Các đối số biến (chính xác mà chúng tôi muốn cung cấp cho std ::bind)

Chúng tôi có thể thay đổi chrono ::mili giây thành nano giây hoặc micro giây, v.v. để thay đổi độ chính xác.

Mã mẫu

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later {
   public:
      template <class callable, class... arguments>
      later(int after, bool async, callable&& f, arguments&&... args){
      std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
      if (async) {
         std::thread([after, task]() {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
         }).detach();
      } else {
         std::this_thread::sleep_for(std::chrono::milliseconds(after));
         task();
      }
   }
};
void test1(void) {
   return;
}
void test2(int a) {
   printf("result of test 2: %d\n", a);
   return;
}
int main() {
   later later_test1(3000, false, &test1);
   later later_test2(1000, false, &test2, 75);
   later later_test3(3000, false, &test2, 101);
}

Đầu ra

$ g++ test.cpp -lpthread
$ ./a.out
result of test 2: 75
result of test 2: 101
$

kết quả đầu tiên sau 4 giây. Kết quả thứ hai sau ba giây kể từ kết quả đầu tiên