Created
November 11, 2022 15:57
-
-
Save newmanjeff/c1fa205efde2358363dc82dcc34d08f0 to your computer and use it in GitHub Desktop.
Test performance of stat vs open on non-existent files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <fcntl.h> | |
#include <sys/stat.h> | |
#include <assert.h> | |
#include <chrono> | |
#include <string> | |
int main (int argc, const char** argv) { | |
if (argc != 2) { | |
fprintf(stderr, "Usage: %s [stat|open]\n", argv[0]); | |
return 1; | |
} | |
std::string syscall_to_test = argv[1]; | |
if (syscall_to_test != "stat" && syscall_to_test != "open") { | |
fprintf(stderr, "Usage: %s [stat|open]\n", argv[0]); | |
return 1; | |
} | |
printf("Calling %s() 10,000 times on non-existent files\n", syscall_to_test.c_str()); | |
auto begin = std::chrono::high_resolution_clock::now(); | |
for (int i = 0; i < 100; i++){ | |
for (int j = 0; j < 100; j++){ | |
std::string path = "/usr/local/lib/file_does_not_exist_" + std::to_string(j); | |
if (syscall_to_test == "stat") { | |
struct stat file_info; | |
int error; | |
error = stat(path.c_str(), &file_info); | |
assert (error != 0); | |
} | |
else { | |
int fd; | |
assert(open(path.c_str(), O_RDONLY) == -1); | |
} | |
} | |
} | |
auto end = std::chrono::high_resolution_clock::now(); | |
auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin); | |
printf("Time measured: %.6f seconds.\n", elapsed.count() * 1e-9); | |
printf("%.2f usec per call.\n", elapsed.count() / 10000 * 1e-3); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment