ウィスコンシン大学が公開している Operating System: Three Easy Pieces の第六章 "Direct Execution" より、システムコールのコストを計測する課題を書いた。
テクストはこれ。末尾に課題の説明がある: https://pages.cs.wisc.edu/~remzi/OSTEP/cpu-mechanisms.pdf
read(2) を 106 回叩いて、時間差をはかる。こういう結果が出た。
0.502876 microsec per syscall (averaged on 1000000 iterations)
コードはこれ
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/time.h> int main() { struct timeval lhs, rhs; int fd = open("./a.txt", O_CREAT); int n = 1000000; gettimeofday(&lhs, NULL); for (size_t i = 0; i < n; i++) { read(fd, NULL, 0); } gettimeofday(&rhs, NULL); printf("%f microsec per syscall (averaged on %d iterations)\n" , (float) ((rhs.tv_sec - lhs.tv_sec) * 1000000 + (rhs.tv_usec - lhs.tv_usec)) / n , n); close(fd); return 0; }