Skip to content

Instantly share code, notes, and snippets.

@Freaky
Last active August 10, 2018 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Freaky/e08d97a7d8893f9468be44bdc4a87354 to your computer and use it in GitHub Desktop.
Save Freaky/e08d97a7d8893f9468be44bdc4a87354 to your computer and use it in GitHub Desktop.
22 seconds -> 8.5 seconds running stat on /usr/src, 24 -> 5.6 seconds on a large Maildir
Index: stat.c
===================================================================
--- stat.c (revision 336221)
+++ stat.c (working copy)
@@ -202,6 +202,30 @@
(*nl) = ((c) == '\n'); \
} while (0/*CONSTCOND*/)
+static struct passwd *
+cached_getpwuid(uid_t uid)
+{
+ static struct passwd *last = NULL;
+
+ if (!last || last->pw_uid != uid) {
+ last = getpwuid(uid);
+ }
+
+ return last;
+}
+
+static struct group *
+cached_getgrgid(gid_t gid)
+{
+ static struct group *last = NULL;
+
+ if (!last || last->gr_gid != gid) {
+ last = getgrgid(gid);
+ }
+
+ return last;
+}
+
int
main(int argc, char *argv[])
{
@@ -717,7 +741,7 @@
case SHOW_st_uid:
small = (sizeof(st->st_uid) == 4);
data = st->st_uid;
- if ((pw = getpwuid(st->st_uid)) != NULL)
+ if ((pw = cached_getpwuid(st->st_uid)) != NULL)
sdata = pw->pw_name;
else {
snprintf(sid, sizeof(sid), "(%ld)", (long)st->st_uid);
@@ -731,7 +755,7 @@
case SHOW_st_gid:
small = (sizeof(st->st_gid) == 4);
data = st->st_gid;
- if ((gr = getgrgid(st->st_gid)) != NULL)
+ if ((gr = cached_getgrgid(st->st_gid)) != NULL)
sdata = gr->gr_name;
else {
snprintf(sid, sizeof(sid), "(%ld)", (long)st->st_gid);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment