2023 talk about flamegraphs
[libguestfs-talks.git] / 2023-flamegraphs / sleeptest.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <sys/time.h>
5 #include <pthread.h>
6
7 #define NR_THREADS 32
8
9 static void *
10 busywork_thread (void *start_vp)
11 {
12   struct timeval *start_t = start_vp;
13   struct timeval t;
14   int i;
15   unsigned a[256] = { 0 };
16
17   while (1) {
18     gettimeofday (&t, NULL);
19     if (t.tv_sec >= start_t->tv_sec + 3 ||
20         (t.tv_sec == start_t->tv_sec + 2 &&
21          t.tv_usec >= start_t->tv_usec))
22       break;
23
24     for (i = 0; i < 256; ++i) {
25       a[i] += t.tv_usec;
26       if (i > 0) a[i] += a[i-1];
27     }
28   }
29   return NULL;
30 }
31
32 static void
33 busywork_2secs (void)
34 {
35   pthread_t thr[NR_THREADS];
36   int i;
37   struct timeval start_t;
38
39   gettimeofday (&start_t, NULL);
40
41   for (i = 0; i < NR_THREADS; ++i)
42     pthread_create (&thr[i], NULL, busywork_thread, &start_t);
43   for (i = 0; i < NR_THREADS; ++i)
44     pthread_join (thr[i], NULL);
45 }
46
47 int
48 main (void)
49 {
50   int i;
51
52   for (i = 0; i < 5; ++i) {
53     busywork_2secs ();
54     sleep (6);
55   }
56   return 0;
57 }