C++实现多线程

#include <iostream>
#include <chrono>
#include <thread>

void printNumbers1() {
   for (int i = 1; i <= 10000; i++) {
      std::cout << "Thread 1: " << i << std::endl;
   }
}

void printNumbers2() {
   for (int i = 1; i <= 10000; i++) {
      std::cout << "Thread 2: " << i << std::endl;
   }
}

int main() {
   auto start_time = std::chrono::high_resolution_clock::now();   // 记录开始时间

   std::thread t1(printNumbers1);
   std::thread t2(printNumbers2);

   t1.join();
   t2.join();

   auto end_time = std::chrono::high_resolution_clock::now();     // 记录结束时间
   auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time); // 计算时间差

   std::cout << "Total time: " << duration_ms.count() << "ms" << std::endl;    // 输出总时间

   return 0;
}

 

posted @ 2023-04-16 14:59  Z_Chan  阅读(24)  评论(0编辑  收藏  举报