Why is the child's lead time negative?

I did a little test to find out how much time a child process is taking with fork () compared to the parent. However, by running this program, I get execution for the child to somehow come up with as negative.

#include <stdio.h>
#include <unistd.h>
#include <time.h>

int main(void){
    clock_t begin = clock();

    printf("Before fork\n");


    pid_t pid_return = fork();


    char* x;

    if(pid_return != 0){
        x = "Parent";
    }
    else{
        x = "Child";
    }

    clock_t end = clock();

    double time_spent = (double)(end - begin);
    printf("%s time spent: %f\n", x, time_spent);
}

Conclusion:

Before fork
Parent time spent: 197.000000
Child time spent: -2143.000000
+4
source share
2 answers

clock()is not (wall clock), this is the amount of CPU used by the current process. Using fork(), you are supposedly reset this time to 0 in the child process (since it hasn't used any CPU yet). This is why it is endmuch smaller in the child element and subtracting the parent beginfrom it makes it negative.

+3

, : parent clock , , clock fork.

:

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

int main(void){
    printf("Before fork\n");
    pid_t pid_return = fork();
    clock_t time = clock();
    char* x;
    if(pid_return != 0){
        x = "Parent";
    } else{
        x = "Child";
    }
    printf("%s time : %f\n", x, (double)time);
}

child, , fork.

Before fork
Parent time : 2684.000000
Child time : 617.000000
+3

Source: https://habr.com/ru/post/1676545/


All Articles