# Running as root because the filesystem root directory will be
 # owned by uid 0, and that's where we're writing.
-python3 -m pytest -v $(dirname $0)/../../../src/test/pybind/test_cephfs.py -k test_create_and_rm_2000_subdir_levels_close_v2
+python3 -m pytest -v $(dirname $0)/../../../src/test/pybind/test_cephfs.py -k test_create_and_rm_2000_subdir_levels_close_v3
 exit 0
 
             stack.append(_get_subdir_path(dirpath))
             continue
 
+def test_create_and_rm_2000_subdir_levels_close_v3(testdir):
+    '''
+    rmdir() perhaps is the one that is probably consuming most of the time in
+    collecting and releasing caps. in v3 instead we check if dir is empty using
+    readdir() and then remove dir if it is empty; else we add to the stack.
+    '''
+    def _rm_or_enstack_dir(dirpath, stack):
+        dir_is_empty = True
+        dh = cephfs.opendir(dirpath)
+
+        de = cephfs.readdir(dh)
+        while de:
+            if de.d_name not in (b'.', b'..'):
+                dir_is_empty = False
+                break
+            de = cephfs.readdir(dh)
+
+        if dir_is_empty:
+            cephfs.rmdir(dirpath)
+            stack.pop()
+        else:
+            if not de:
+                raise RuntimeError('unexpectedly "de" is None')
+            stack.append(os.path.join(dirpath, de.d_name))
+
+    LEVELS = 2000
+
+    for i in range(1, LEVELS + 1):
+        dirname = f'dir{i}'
+        cephfs.mkdir(dirname, 0o755)
+        cephfs.chdir(dirname)
+    cephfs.chdir('/')
+
+    stack = collections.deque([b'dir1/',])
+    while stack:
+        dirpath = stack[-1]
+        _rm_or_enstack_dir(dirpath, stack)
+
 def test_ceph_mirror_xattr(testdir):
     def gen_mirror_xattr():
         cluster_id = str(uuid.uuid4())