Monday 27 April 2015

xargs versus exec {}

Time take for execution is very important when we are dealing with scripts or programs.

This is where xargs shows its superiority. When we use -exec to do the work we run a separate instance of program for each input. Suppose, if  "find" command  comes up with 10,000 results, exec has to run 10,000 times. 

xargs build up the input into bundles and run them through the command as few times as possible, mostly just once. When dealing with hundreds or thousands of files this is a great advantage of xargs.

Lets, take each case one by one. 

Case 1: In this case, I am using exec to list all files with extension ".ko" in my machine. The command used is as below:
-----
time find / -name "*.ko" -exec ls {} \; |wc -l
-----



I have 1982 such files in my machine. The time taken to complete the execution of above command is "2.576s". Not bad, right?

Case 2: In this case, I am using xargs for the same scenario. The command used is as below:
------
time find / -name "*.ko" -print0 | xargs -0 ls | wc -l
-------


Now, as the screenshot above proves, the time has been reduced to "0.176s". 

Surely, this time variation between two commands can play a very important role while dealing with large number of files.

Kool :)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.