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