/*
任务6（任选）：测量和比较fork、pthread_create函数调用所需的执行时间，并进行解释。
可以多次反复调用读写函数，计算累积时间。
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/wait.h>

#define ITERATIONS 1000

double get_time()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec + tv.tv_usec / 1000000.0;
}

void *dummy_thread(void *arg)
{
    return NULL;
}

double measure_fork_create()
{
    double t_start = get_time();
    for (int i = 0; i < ITERATIONS; i++)
    {
        pid_t pid = fork();
        if (pid < 0)
        {
            perror("fork");
            exit(1);
        }
        if (pid == 0)
        {
            /* 子进程立即退出 */
            _exit(0);
        }
        else
        {
            /* 父进程等待子进程结束 */
            waitpid(pid, NULL, 0);
        }
    }
    double t_end = get_time();
    return (t_end - t_start) / ITERATIONS;
}

double measure_pthread_create()
{
    pthread_t tid;
    double t_start = get_time();
    for (int i = 0; i < ITERATIONS; i++)
    {
        pthread_create(&tid, NULL, dummy_thread, NULL);
        pthread_join(tid, NULL);
    }
    double t_end = get_time();
    return (t_end - t_start) / ITERATIONS;
}

int main()
{
    printf("Measuring fork() and pthread_create() overhead...\n");
    printf("Iterations per test: %d\n\n", ITERATIONS);

    double avg_pthread_time = measure_pthread_create();
    printf("Average pthread_create() + pthread_join() time: %.6f ms\n",
           avg_pthread_time * 1000);

    double avg_fork_time = measure_fork_create();
    printf("Average fork() + waitpid() time:           %.6f ms\n",
           avg_fork_time * 1000);

    return 0;
}
