我想比较两个进程之间使用Unix域套接字的性能与另一种IPC的性能。
我有一个基本程序,创建一个套接字对,然后调用fork。然后,它测量将8192字节发送到其他进程并返回的往返时间(每次迭代都不同)。
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
int main(int argc, char **argv) {
int i, pid, sockpair[2];
char buf[8192];
struct timespec tp1, tp2;
assert(argc == 2);
// Create a socket pair using Unix domain sockets with reliable,
// in-order data transmission.
socketpair(AF_UNIX, SOCK_STREAM, 0, sockpair);
// We then fork to create a child process and then start the benchmark.
pid = fork();
if (pid == 0) { // This is the child process.
for (i = 0; i < atoi(argv[1]); i++) {
assert(recv(sockpair[1], buf, sizeof(buf), 0) > 0);
assert(send(sockpair[1], buf, sizeof(buf), 0) > 0);
}
} else { // This is the parent process.
for (i = 0; i < atoi(argv[1]); i++) {
memset(buf, i, sizeof(buf));
buf[sizeof(buf) - 1] = '\0';
assert(clock_gettime(CLOCK_REALTIME, &tp1) == 0);
assert(send(sockpair[0], buf, sizeof(buf), 0) > 0);
assert(recv(sockpair[0], buf, sizeof(buf), 0) > 0);
assert(clock_gettime(CLOCK_REALTIME, &tp2) == 0);
printf("%lu ns\n", tp2.tv_nsec - tp1.tv_nsec);
}
}
return 0;
}
然而,我注意到对于每次重复测试,第一次运行的经过时间(i = 0)总是一个异常值:
79306 ns
18649 ns
19910 ns
19601 ns
...
我想知道内核在第一次调用send()
时是否需要进行一些最终设置,例如,在内核中分配8192字节以缓冲在send()
和recv()
之间的数据?
struct timespec
差异时,您可能不想忘记tv_sec
。当秒增加并且您将负纳秒差异格式化为%lu
时,那将看起来像一个很大的数字。 - pilcrow