Thread_bench.cc revision b9b67c9b
1b9b67c9bSShuo Chen#include "../Thread.h"
2b9b67c9bSShuo Chen#include "../../datetime/Timestamp.h"
3b9b67c9bSShuo Chen
4b9b67c9bSShuo Chen#include <sys/wait.h>
5b9b67c9bSShuo Chen
6b9b67c9bSShuo Chenvoid threadFunc()
7b9b67c9bSShuo Chen{
8b9b67c9bSShuo Chen  printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid());
9b9b67c9bSShuo Chen  sleep(10);
10b9b67c9bSShuo Chen}
11b9b67c9bSShuo Chen
12b9b67c9bSShuo Chenvoid threadFunc2()
13b9b67c9bSShuo Chen{
14b9b67c9bSShuo Chen}
15b9b67c9bSShuo Chen
16b9b67c9bSShuo Chenvoid forkBench()
17b9b67c9bSShuo Chen{
18b9b67c9bSShuo Chen  sleep(10);
19b9b67c9bSShuo Chen  muduo::Timestamp start(muduo::Timestamp::now());
20b9b67c9bSShuo Chen  int kProcesses = 10*1000;
21b9b67c9bSShuo Chen
22b9b67c9bSShuo Chen  for (int i = 0; i < kProcesses; ++i)
23b9b67c9bSShuo Chen  {
24b9b67c9bSShuo Chen    pid_t child = fork();
25b9b67c9bSShuo Chen    if (child == 0)
26b9b67c9bSShuo Chen    {
27b9b67c9bSShuo Chen      exit(0);
28b9b67c9bSShuo Chen    }
29b9b67c9bSShuo Chen    else
30b9b67c9bSShuo Chen    {
31b9b67c9bSShuo Chen      waitpid(child, NULL, 0);
32b9b67c9bSShuo Chen    }
33b9b67c9bSShuo Chen  }
34b9b67c9bSShuo Chen
35b9b67c9bSShuo Chen  double timeUsed = timeDifference(muduo::Timestamp::now(), start);
36b9b67c9bSShuo Chen  printf("process creation time used %.3f us\n", timeUsed*1000000/kProcesses);
37b9b67c9bSShuo Chen  printf("number of created processes %d\n", kProcesses);
38b9b67c9bSShuo Chen}
39b9b67c9bSShuo Chen
40b9b67c9bSShuo Chenint main()
41b9b67c9bSShuo Chen{
42b9b67c9bSShuo Chen  printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid());
43b9b67c9bSShuo Chen
44b9b67c9bSShuo Chen  muduo::Thread t1(threadFunc, "Thread 1");
45b9b67c9bSShuo Chen  t1.start();
46b9b67c9bSShuo Chen  t1.join();
47b9b67c9bSShuo Chen
48b9b67c9bSShuo Chen  muduo::Timestamp start = muduo::Timestamp::now();
49b9b67c9bSShuo Chen  const int kThreads = 100 * 1000;
50b9b67c9bSShuo Chen  for (int i = 0; i < kThreads; ++i) {
51b9b67c9bSShuo Chen    muduo::Thread t1(threadFunc2);
52b9b67c9bSShuo Chen    t1.start();
53b9b67c9bSShuo Chen    t1.join();
54b9b67c9bSShuo Chen  }
55b9b67c9bSShuo Chen  muduo::Timestamp end = muduo::Timestamp::now();
56b9b67c9bSShuo Chen  double seconds = timeDifference(end, start);
57b9b67c9bSShuo Chen  printf("created and joined %d threads in %.3f ms, %.3fus per thread.\n",
58b9b67c9bSShuo Chen         kThreads, 1e3 * seconds, 1e6 * seconds / kThreads);
59b9b67c9bSShuo Chen
60b9b67c9bSShuo Chen  forkBench();
61b9b67c9bSShuo Chen}
62