I have been developing a system that polls a series of machines every minute. The OS of all hosts is RedHat Enterprise Linux 4. The less time that process takes, the better. The polling process involves looping over an array and pinging each host. I don't care about the output from ping, just the return value. I was checking via
Well, mistake #1 was using -w instead of -c. I thought what I was doing was saying ping the host once and wait a maximum of a second. What it really meant is ping it as many times as you can in a second! I wrote a benchmarking program to time various calls to ping (using Time::HiRes) and found that once I added `-c 1`, none of the other switches was really making a difference (-a, -r, etc). I found that system("ping -q -w 1 -c 1 $host > /dev/null 2>&1"), instead of taking ~1.008 seconds, took ~.0085 seconds!if ( !( system("ping -q -w 1 $host > /dev/null 2>&1") ) ) { #do something } else { #report the failure }
I acknowledge that any sane person would have stopped here. 8.5 milliseconds is pretty trivial in terms of a program that runs 17 times a minute (as opposed to 1.0085 milliseconds). I also must note that the procedure is neither scientific not statistically valid. However, I'd be willing to bet I could show significance (I've messed around with more rigorous methods before as here)
Well, being the habitual tinkerer that I am, I was wondering if there was any more savings to be had, and I focused on overhead of redirecting the output. I tried a bunch of different forms of redirecting output to /dev/null, with no results. So I tried
`ping -q -w 1 -c 1 $host`; #(void context)--it reduced the average time from ~.008 seconds to ~.0045 seconds! I tried using a dummy variable:
my $dummy_var=`ping -q -w 1 -c 1 $host`;That didn't seem to have any impact on the time.
By the principles of maintainable code, if one doesn't care about the output, one shouldn't capture it--even with a comment, it's like, "why?" (besides blind adherence to a rule on a FAQ). Not to mention the (likely negligible) overhead of assigning to a variable. Seems like void backticks is the way to go here, (with a comment of course) though I admit I haven't checked to see if having to test $? in a separate statement kills the savings. (I'd wager it doesn't)
Are there other ways that might be even more efficient? I'd be happy to benchmark them.
UPDATE: since diotalevi asked in the CB, redirecting to /dev/null in the backticks call imposes the same penalty.
UPDATE: Changed the title
In reply to I thought I found a good reason to use backticks in a void context, but I was wrong. by OfficeLinebacker
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |