如何计算C中fork()系统调用的运行时间?

kaf*_*f89 6 c time fork child-process

我正在尝试查找fork()系统调用的运行时间.每个子进程都需要立即退出,父进程需要在每个子进程wait()创建下一个进程之前.我还想使用命名的shell内置命令time来测量程序的执行时间.

到目前为止我有这个代码,但不确定如果我做得对.

#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int global = 100;

int main(int argc, char** argv)
{
    int local = 5;

    pid_t pid;

    pid = fork();
    if (pid < 0) {
        fprintf(stderr, "error -- failed to fork()");
        return 1;
    }

    if (pid > 0) {

        int child_ret;

        waitpid(pid, &child_ret, 0);
        printf("parent -- global: %i, local: %i\n", global, local);
        printf("parent -- child exited with code %i\n", child_ret);
    } else {
        global++;
        local++;

        printf("child -- global: %i, local: %i\n", global, local);
        exit (0);
    }
}
Run Code Online (Sandbox Code Playgroud)

Bas*_*tch 2

阅读第一次(7)并考虑使用clock_gettime(2)getrusage(2)如果您只想测量fork(2)系统调用本身的时间(它非常小 - 可能是一毫秒 - 并且并不真正重要),您可以使用clock_gettimearound (在父进程中)。fork

在失败情况下使用errno(例如 printstrerror(errno)或 use )。perror

请注意,fork时间可能稍微取决于虚拟地址空间的大小和驻留集大小。你也可以使用strace计时能力;在实践中fork足够快(通常不到一毫秒,有时几十微秒;因为它使用惰性写入时复制技术)

因此速度fork很快,子进程execve 可能需要多花几微秒,子进程中的程序启动时间也很重要(ld-linux(8)在您的-ed 程序启动之前执行一些重定位...)。您到底想测量什么?mainexec

一般来说,子进程快速调用execve(2),这也需要一些时间(当然,执行的程序可能需要一段任意长的时间才能完成,如果是类似服务器的程序,甚至可能“永远不会”完成)。也许重要的是子进程中的-d 程序之前fork 和第一个有意义的指令之间的时间......mainexecve

事实上,你可以启动很多进程;经验法则是fork每秒最多执行数百次,并且只有当孩子快速 execve执行某些快速程序(例如/bin/ls几十个文件或date)时。但是,您不希望同时拥有超过一打或两个可运行进程(在笔记本电脑或台式机上),甚至可能少于 5 个可运行进程......