优秀的编程知识分享平台

网站首页 > 技术文章 正文

Linux 下海量文件删除方法效率对比,最慢的竟然是 rm

nanyue 2025-02-20 17:14:15 技术文章 3 ℃


Linux 下海量文件删除方法效率对比,本次参赛选手一共6位,分别是:rm、find、find with delete、rsync、Python、Perl.

首先建立50万个文件

$ test   for i in $(seq 1 500000);do echo text >>$i.txt;done
  1. rm 删除
$ time rm -f *
zsh: sure you want to delete all the files in /home/hungerr/test [yn]? y
zsh: argument list too long: rm
rm -f *  3.63s user 0.29s system 98% cpu 3.985 total
# 由于文件数量过多,rm不起作用。
  1. find 删除
 $ time find ./ -type f -exec rm {} \;
 find ./ -type f -exec rm {} \;  49.86s user 1032.13s system 41% cpu 43:19.17 total#
 # 大概43分钟,我的电脑。。。。。。边看视频边删的。
  1. find with delete
$ time find ./ -type f -delete
find ./ -type f -delete  0.43s user 11.21s system 2% cpu 9:13.38 total
# 用时9分钟。
  1. rsync 删除
# 首先建立空文件夹blanktest
$ time rsync -a --delete blanktest/ test/
rsync -a --delete blanktest/ test/  0.59s user 7.86s system 51% cpu 16.418 total16s,很好很强大。
  1. Python 删除
import os
import timeit
def main():    for pathname,dirnames,filenames in os.walk('/home/username/test'):        for filename in filenames:            
		file=os.path.join(pathname,filename)            
		os.remove(file)            
if __name__=='__main__':
t=timeit.Timer('main()','from __main__ import main')
print t.timeit(1)  

$ python test.py
529.309022903
# 大概用时9分钟。
  1. Perl 删除
$ time perl -e 'for(<*>){((stat)[9]<(unlink))}'
perl -e 'for(<*>){((stat)[9]<(unlink))}'  1.28s user 7.23s system 50% cpu 16.784 total16s,这个应该最快了。

测试结果

  • rm:文件数量太多,不可用
  • find with -exec 50万文件耗时43分钟
  • find with -delete 9分钟
  • Perl 16sPython 9分钟
  • rsync with -delete 16s

结论:删除大量小文件rsync最快,最方便

最近发表
标签列表