哪一个工作得更快 - 常规操作员(例如<、>、=)或使用(-lt、-gt、-eq)?为什么?
答案1
您可以简单地使用命令来比较这些运算符的性能time
:
time [ 1 -eq 0 ] real 0m0.000s user 0m0.000s sys 0m0.000s
time [ 1 = 0 ] real 0m0.000s user 0m0.000s sys 0m0.000s
这是real
意味着挂钟时间和user
手段用户空间时间和sys
手段系统或内核时间。
现在,如果您将这些运算符与time
包含以下行的脚本的外部命令进行比较,您将看到类似的输出:
Sepahrad@localhost 15:17:13 [~]$cat test.sh
#!/bin/bash [ 1 -eq 0 ] echo $?
Sepahrad@localhost 15:17:13 [~]$cat test1.sh
#!/bin/bash [ 1 == 0 ] echo $?
现在运行外部time
命令,您将再次看到类似的输出:
/usr/bin/time ./test.sh
或者/usr/bin/time ./test1.sh
1 0.00user 0.00system 0:00.00elapsed 50%CPU (0avgtext+0avgdata 4752maxresident)k 0inputs+0outputs (0major+331minor)pagefaults 0swaps
现在我们看一下命令的源代码:(源代码bash
可以从bash
http://www.gnu.org/software/bash/并查看test.c
文件)
int
binary_test (op, arg1, arg2, flags)
char *op, *arg1, *arg2;
int flags;
{
int patmatch;
patmatch = (flags & TEST_PATMATCH);
if (op[0] == '=' && (op[1] == '\0' || (op[1] == '=' && op[2] == '\0')))
return (patmatch ? patcomp (arg1, arg2, EQ) : STREQ (arg1, arg2));
else if ((op[0] == '>' || op[0] == '<') && op[1] == '\0')
{
#if defined (HAVE_STRCOLL)
if (shell_compatibility_level > 40 && flags & TEST_LOCALE)
return ((op[0] == '>') ? (strcoll (arg1, arg2) > 0) : (strcoll (arg1, arg2) < 0));
else
#endif
return ((op[0] == '>') ? (strcmp (arg1, arg2) > 0) : (strcmp (arg1, arg2) < 0));
}
else if (op[0] == '!' && op[1] == '=' && op[2] == '\0')
return (patmatch ? patcomp (arg1, arg2, NE) : (STREQ (arg1, arg2) == 0));
else if (op[2] == 't')
{
switch (op[1])
{
case 'n': return (filecomp (arg1, arg2, NT)); /* -nt */
case 'o': return (filecomp (arg1, arg2, OT)); /* -ot */
case 'l': return (arithcomp (arg1, arg2, LT, flags)); /* -lt */
case 'g': return (arithcomp (arg1, arg2, GT, flags)); /* -gt */
}
}
else if (op[1] == 'e')
{
switch (op[2])
{
case 'f': return (filecomp (arg1, arg2, EF)); /* -ef */
case 'q': return (arithcomp (arg1, arg2, EQ, flags)); /* -eq */
}
}
else if (op[2] == 'e')
{
switch (op[1])
{
case 'n': return (arithcomp (arg1, arg2, NE, flags)); /* -ne */
case 'g': return (arithcomp (arg1, arg2, GE, flags)); /* -ge */
case 'l': return (arithcomp (arg1, arg2, LE, flags)); /* -le */
}
}
return (FALSE); /* should never get here */
}
你会看到-eq
will 用这一行解释:
case 'q': return (arithcomp (arg1, arg2, EQ, flags)); /* -eq
并将=
解释为:
if (op[0] == '=' && (op[1] == '\0' || (op[1] == '=' && op[2] == '\0')))
return (patmatch ? patcomp (arg1, arg2, EQ) : STREQ (arg1, arg2));
与>
或<
运算符将解释为:
else if ((op[0] == '>' || op[0] == '<') && op[1] == '\0')
{
#if defined (HAVE_STRCOLL)
if (shell_compatibility_level > 40 && flags & TEST_LOCALE)
return ((op[0] == '>') ? (strcoll (arg1, arg2) > 0) : (strcoll (arg1, arg2) < 0));
else
#endif
return ((op[0] == '>') ? (strcmp (arg1, arg2) > 0) : (strcmp (arg1, arg2) < 0));
}
和-gt
or-lt
将解释为:
case 'l': return (arithcomp (arg1, arg2, LT, flags)); /* -lt */
case 'g': return (arithcomp (arg1, arg2, GT, flags)); /* -gt */
结论:正如您在bash
源代码中看到的这些运算符用不同的函数解释的那样,但我认为性能与您在命令中看到的没有差异time
!