博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何在Linux上使用time命令
阅读量:2507 次
发布时间:2019-05-11

本文共 11534 字,大约阅读时间需要 38 分钟。

Linux PC with a terminal window open

Want to know how long a process runs and a whole lot more? The Linux time command returns time statistics, giving you cool insights into the resources used by your programs.

是否想知道一个流程运行了多长时间? Linux time命令返回时间统计信息,使您可以很深入地了解程序所使用的资源。

时间有很多亲戚 (time Has Many Relatives)

There are many Linux distributions and different Unix-like operating systems. Each of these has a default command shell. The most common default shell in modern Linux distributions is the bash shell. But there are many others, such as the Z shell (zsh) and the Korn shell (ksh).

有许多Linux发行版和不同的类Unix操作系统。 每个都有一个默认的命令外壳。 现代Linux发行版中最常见的默认shell是bash shell。 但是还有许多其他内容,例如Z shell(zsh)和Korn shell(ksh)。

All of these shells incorporate their own time command, either as a  command or as a . When you type time in a terminal window the shell will execute its internal command instead of using the GNU time binary which is provided as part of your Linux distribution.

所有这些外壳程序都结合了自己的time命令,可以作为命令或作为 。 在终端窗口中键入time ,shell将执行其内部命令,而不使用Linux发行版中提供的GNU time二进制文件。

We want to use the GNU version of time because it has more and is more flexible.

我们希望使用time的GNU版本,因为它具有更多的并且更加灵活。

哪个时间运行? (Which time Will Run?)

You can check which version will run by using the type command. type will let you know whether the shell will handle your instruction itself, with its internal routines, or pass it on to the GNU binary.

您可以使用type命令检查运行哪个版本。 type将使您知道shell是使用自身的内部例程来处理指令本身,还是将其传递给GNU二进制文件。

in a terminal window type the word type, a space, and then the word time and hit Enter.

在终端窗口中,输入单词type ,空格,然后输入time并按Enter。

type time
type time in a bash terminal window

We can see that in the bash shell time is a reserved word. This means Bash will use its internaltime routines by default.

我们可以看到,在bash shell中, time是保留字。 这意味着Bash将默认使用其内部time例程。

type time
type time in a zsh terminal window

In the Z shell (zsh) time is a reserved word, so the internal shell routines will be used by default.

在Z shell(zsh)中, time是保留字,因此默认情况下将使用内部shell例程。

type time
type time in a Korn shell window

In the Korn shell time is a keyword. An internal routine will be used instead of the GNU time command.

在Korn Shell中, time是一个关键字。 将使用内部例程代替GNU time命令。

运行GNU time命令 (Running the GNU time Command)

If the shell on your Linux system has an internal time routine you’ll need to be explicit if you wish to use the GNU time binary. You must either:

如果Linux系统上的Shell具有内部time例程,则希望使用GNU time二进制文件时必须明确。 您必须:

  • Provide the whole path to the binary, such as  /usr/bin/time. Run the which time command to find this path.

    提供二进制文件的完整路径,例如/usr/bin/time 。 运行which time命令以查找此路径。

  • Use command time.

    使用command time

  • Use a backslash like \time.

    使用反斜杠,例如\time

time command output in a terminal window

The which time command gives us the path to the binary.

which time命令为我们提供了二进制文件的路径。

We can test this by using /usr/bin/time as a command to launch the GNU binary. That works. We get a response from the time command telling us we didn’t provide any command line parameters for it to work on.

我们可以通过使用/usr/bin/time作为启动GNU二进制文件的命令来进行测试。 这样可行。 我们从time命令得到了一个响应,告诉我们我们没有提供任何命令行参数来运行它。

Typing command time also works, and we get the same usage information from time. The command command tells the shell to ignore the next command so that it is processed outside of the shell.

输入command time也可以,并且我们从time获得相同的用法信息。 command命令告诉外壳程序忽略下一个命令,以便在外壳程序外对其进行处理。

Using a \ character before the command name is the same as using command before the command name.

在命令名称前使用\字符与在命令名称前使用command相同。

The simplest way to ensure you are using the GNU time binary is to to use the backslash option.

确保使用GNU time二进制文件的最简单方法是使用反斜杠选项。

time
\time
time and \time output in a terminal window

time invokes the shell version of time. \time uses the time binary.

time调用time外壳版本。 \time使用time 二进制文件

使用时间命令 (Using The time Command)

Let’s time some programs. We’re using two programs called loop1 and loop2. They were created from loop1.c and loop2.c. They don’t do anything useful apart from demonstrating the effects of one type of coding inefficiency.

让我们来计时一些程序。 我们正在使用两个名为loop1loop2程序。 它们是从loop1.c和loop2.c创建的。 除了证明一种编码效率低下的影响外,它们没有任何有用的作用。

This is loop1.c. The length of a string is required within the two nested loops. The length is obtained in advance, outside of the two nested loops.

这是loop1.c。 在两个嵌套循环中,字符串的长度是必需的。 该长度是在两个嵌套循环之外预先获得的。

#include "stdio.h"#include "string.h"#include "stdlib.h"int main (int argc, char* argv[]){ int i, j, len, count=0; char szString[]="how-to-geek-how-to-geek-how-to-geek-how-to-geek-how-to-geek-how-to-geek"; // get length of string once, outside of loops len = strlen( szString );   for (j=0; j<500000; j++) { for (i=0; i < len; i++ ) {  if (szString[i] == '-')    count++;   } } printf("Counted %d hyphens\n", count); exit (0);} // end of main

This is loop2.c. The length of the string is obtained time after time for every cycle of the outer loop. This inefficiency ought to show up in the timings.

这是loop2.c。 字符串的长度是在外循环的每个循环中一次又一次地获得的。 这种低效率应该在时机上体现出来。

#include "stdio.h"#include "string.h"#include "stdlib.h"int main (int argc, char* argv[]){ int i, j, count=0; char szString[]="how-to-geek-how-to-geek-how-to-geek-how-to-geek-how-to-geek-how-to-geek"; for (j=0; j<500000; j++) { // getting length of string every // time the loops trigger for (i=0; i < strlen(szString); i++ ) {   if (szString[i] == '-')    count++;   } } printf("Counted %d hyphens\n", count); exit (0);} // end of main

Let’s fire up the loop1 program and use time to measure its performance.

让我们启动loop1程序并使用time来衡量其性能。

\time ./loop1
time results for loop1 in a terminal window

Now let’s do the same for loop2.

现在让我们对loop2做同样的事情。

\time ./loop2
time output for loop2 in a terminal window

That’s given us two sets of results, but they’re in a really ugly format. We can do something about that later, but let’s pick a few bits of information out of the results.

这给了我们两组结果,但是它们的格式非常难看。 我们稍后可以做一些事情,但是让我们从结果中挑选一些信息。

When programs run there are two execution modes that they are switched back and forth between. These are called user mode and kernel mode.

程序运行时,有两种执行模式可以在它们之间来回切换。 这些称为用户模式内核模式

Briefly put, a process in user mode cannot directly access hardware or reference memory outside of its own allocation. In order to get access to such resources, the process must make requests to the kernel. If the kernel approves the request the process enters kernel mode execution until the requirement has been satisfied. The process is then switched back to user mode execution.

简而言之,用户模式下的进程无法直接访问其自身分配之外的硬件或参考内存。 为了获得对此类资源的访问,进程必须向内核发出请求。 如果内核批准了该请求,则过程将进入内核模式执行,直到满足要求为止。 然后,该过程切换回用户模式执行。

The results for loop1 tell us that loop1 spent 0.09 seconds in user mode. It either spent zero time in kernel mode or the time in kernel mode is too low a value to register once it has been rounded down. The total elapsed time was 0.1 seconds. loop1 was awarded an average of 89% of CPU time over the duration of its total elapsed time.

loop1的结果告诉我们, loop1在用户模式下花费了0.09秒。 舍入后,它要么在内核模式下花费了零时间,要么在内核模式下的时间太短而无法注册。 总经过时间为0.1秒。 loop1在其总经过时间中平均获得了89%的CPU时间。

The inefficient loop2 program took three times longer to execute. Its total elapsed time is 0.3 seconds. The duration of the processing time in user mode is 0.29 seconds. Nothing is registering for kernel mode. loop2 was awarded an average of 96% of CPU time for the duration of its run.

低效的loop2程序执行时间要长三倍。 它的总耗时为0.3秒。 用户模式下的处理时间为0.29秒。 什么都没有注册内核模式。 loop2在其运行期间平均获得了96%的CPU时间。

格式化输出 (Formatting The Output)

You can customize the output from time using a format string. The format string can contain text and format specifiers. The list of format specifiers can be for time. Each of the format specifiers represents a piece of information.

您可以自定义输出time使用的格式字符串。 格式字符串可以包含文本和格式说明符。 格式说明符列表可以找到time 。 每个格式说明符代表一条信息。

When the string is printed the format specifiers are replaced by the actual values they represent. For example, the format specifier for the percentage of CPU is the letter P . To indicate to time that a format specifier is not just a regular letter, add a percentage sign to it, like %P . Let’s use it in an example.

打印字符串时,格式说明符将替换为它们所代表的实际值。 例如,CPU百分比的格式说明符为字母P 来指示time ,一个格式说明不只是一个普通的字母,加上百分号它,就像%P 。 让我们在示例中使用它。

The -f (format string) option is used to tell time that what follows is a format string.

-f (格式字符串)选项用于告诉time紧随其后的是格式字符串。

Our format string is going to print the characters “Program: ” and the name of the program (and any command line parameters that you pass to the program). The %C format specifier stands for “Name and command-line arguments of the command being timed”. The \n causes the output to move to the next line.

我们的格式字符串将打印字符“ Program:”和程序名称(以及传递给该程序的所有命令行参数)。 %C格式说明符表示“正在计时的命令的名称和命令行参数”。 \n导致输出移至下一行。

There are a lot of formats specifiers and they are case sensitive, so make sure you are entering them correctly when you’re doing this for yourselves.

格式说明符很多,而且区分大小写,因此请确保自己进行正确输入时正确输入它们。

Next, we’re going to print the characters “Total time: ” followed by the value of the total elapsed time for this run of the program (represented by %E).

接下来,我们将打印字符“ Total time:”,后跟该程序运行的总经过时间值(以%E表示)。

We use \n to give another new line. We’ll then print the characters “User Mode (s) “, followed by the value of the CPU time spent in user mode, signified by the %U.

我们使用\n换行。 然后,我们将打印字符“ User Mode(s)”,然后打印在用户模式下花费的CPU时间值,以%U表示。

We use \n to give another new line. This time we are preparing for the kernel time value. We print the characters “Kernel Mode (s) “, followed by the format specifier for CPU time spent in kernel mode, which is %S.

我们使用\n换行。 这次我们正在准备内核时间值。 我们打印字符“ Kernel Mode(s)”,然后打印用于内核模式的CPU时间的格式说明符%S

Finally, we are going to print the characters “\nCPU: ” to give us a new line and the title for this data value. The %P format specifier will give the average percentage of CPU time used by the timed process.

最后,我们将打印字符“ \n CPU:”,以换行并显示此数据值的标题。 %P格式说明符将给出定时进程使用的平均CPU时间百分比。

The whole format string is wrapped in quotation marks. We could have included some \t characters to place tabs in the output if we were fussy about the alignment of the values.

整个格式字符串都用引号引起来。 如果我们对值的对齐很挑剔,我们可以在输出中包含一些\t字符来放置制表符。

\time -f "Program: %C\nTotal time: %E\nUser Mode (s) %U\nKernel Mode (s) %S\nCPU: %P" ./loop1
Output from format string for loop1 in a terminal window

将输出发送到文件 (Sending The Output To A File)

To keep a record of the timings from the tests you have conducted you can send the output from time to a file. To do this use the -o (output) option. The output from your program will still display in the terminal window. It is only the output from time that is redirected to the file.

要记录您进行的测试的时间,可以将输出信息time地发送到文件中。 为此,请使用-o (输出)选项。 程序的输出仍将显示在终端窗口中。 只有time的输出才重定向到文件。

We can re-run the test and save the output to the test_results.txt file as follows:

我们可以重新运行测试,并将输出保存到test_results.txt文件,如下所示:

\time -o test_results.txt -f "Program: %C\nTotal time: %E\nUser Mode (s) %U\nKernel Mode (s) %S\nCPU: %P" ./loop1
cat test_results.txt
Output from format string for loop1 piped to file in a terminal window

The loop1 program output is displayed in the terminal window and the results from time go to the test_results.txt file.

loop1程序的输出将显示在终端窗口中,并且time的结果将进入test_results.txt文件。

If you want to capture the next set of results in the same file, you must use the -a (append) option as follows:

如果要在同一文件中捕获下一组结果,则必须使用-a (附加)选项,如下所示:

\time -o test_results.txt -a -f "Program: %C\nTotal time: %E\nUser Mode (s) %U\nKernel Mode (s) %S\nCPU: %P" ./loop2
cat test_results.txt
Output from format string for loop2 appended to file in a terminal window

It should now be apparent why we used the %C format specifier to include the name of the program in the output from the format string.

现在显而易见,为什么我们使用%C格式说明符在格式字符串的输出中包括程序名称。

而且我们没时间了 (And We’re Out Of time)

Probably of most use to programmers and developers for fine-tuning their code, the time command is also useful for anyone wanting to discover a bit more about what goes on under the hood each time you launch a program.

time命令可能最适合程序员和开发人员用于微调他们的代码,对于任何想在每次启动程序时了解幕后情况的人来说, time命令也很有用。

翻译自:

转载地址:http://rpkwd.baihongyu.com/

你可能感兴趣的文章
CString的成员函数详解
查看>>
Appium Studio 初体验(windows做ios自动化,录制appium脚本)
查看>>
学习java前端 两种form表单提交方式
查看>>
Linux常用命令
查看>>
整体二分&cdq分治 ZOJ 2112 Dynamic Rankings
查看>>
【POJ2976】Dropping tests (01分数规划入门题)
查看>>
无法变更启动序列号
查看>>
Linux修改密码指令
查看>>
算法(第四版)C# 习题题解——2.1
查看>>
通过正则表达式获取url中参数
查看>>
追加模式 文件读写
查看>>
86.运算符重载
查看>>
47.使用帧缓存对象生成叠加
查看>>
思考:有三扇门,其中一扇门里有奖品,三选一,你选择其中一扇门之后,主持人先不揭晓答案,而是从另外两扇门中排除掉一个没有奖品的门,现在主持人问你,要不要换个门,请问你换还是不换?...
查看>>
Linux PATH 添加(永久有效)
查看>>
dyld: Library not loaded: @rpath/libswiftCore.dylib
查看>>
Python 爬虫-Requests库入门
查看>>
Java Spring-Bean
查看>>
Improve Score Better With AWS-Solution-Architect-Associate Exam Cram
查看>>
Vue 封装可向左向右查看图片列表的组件
查看>>