我正在嘗試 CoW fork(有關更詳細的背景,請參閱編輯,這可能非常不相關)
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#define N 262144
struct {
int n;
int padding[1023];
} arr[N];
int main() {
int i, sp = 0, t, tx = clock();
for (i=0; i<N; i) arr[i].n = i;
printf ("Init Time: %d\n", clock()-tx);
#if 1
sp = fork();
if(!sp) _exit(0);
waitpid(sp, &sp, 0);
#endif
// 5045 without fork
// 104192 with fork
t = clock();
for (i=0; i<N; i) arr[i].n = -i;
printf ("Runner %d Time: %d\n", sp, clock() - t);
getchar();
return 0;
}
這fork使得后面的記憶體訪問變慢。
不要fork復制使其慢?如果是這樣,為什么?我在 Ubuntu 20.04.3 LTS 上運行
uj5u.com熱心網友回復:
嘗試運行它/usr/bin/time -v并觀察 Minor (reclaiming a frame) page faults:線路。
即使孩子立即退出,叉子也會使其翻倍。
增加的時間似乎完全是由于這些頁面錯誤。
據推測,在 fork 時,內核將頁面設定為在寫入時出錯,以期需要復制。如果在這種頁面錯誤時孩子已經死了,復制的需要就會被取消(該頁面不再與任何人共享,因此無需費心復制它),但您仍然需要為頁面錯誤命中付出代價。
現在,如果你讓孩子活著,那么頁面錯誤處理程式也應該需要做復制,事實上,讓孩子活著會增加回圈持續時間數倍。那應該是完整的寫時復制。
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#define N 262144
struct {
int n;
int padding[1023];
} arr[N];
int main() {
int i, t, tx = clock();
pid_t sp=0;
for (i=0; i<N; i) arr[i].n = i;
printf ("Init Time: %ld\n", clock()-tx);
#if 1
if(0>(sp = fork())) return 1;
enum { KEEP_THE_KID_EH = 1 };
if(!sp){ if(KEEP_THE_KID_EH){ for(;;) pause(); } exit(0); }
#endif
t = clock();
for (i=0; i<N; i) arr[i].n = -i;
printf ("Runner %ld Time: %ld\n", (long)sp, clock() - t);
/*getchar();*/
if(sp) kill(sp,SIGTERM);
return 0;
}
我的時間是:
7371 without fork
189073 with fork
1092145 with fork and the kid kept
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359444.html
