bash ZSH:如何对代码块计时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6693515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:22:29  来源:igfitidea点击:

ZSH: How to time a block of code?

bashzsh

提问by cldfzn

In bash I am able to write a script that contains something like this:

在 bash 中,我能够编写一个包含以下内容的脚本:

{ time {

#series of commands
echo "something"
echo "another command"
echo "blah blah blah"

} } 2> $LOGFILE

In ZSH the equivalent code does not work and I can not figure out how to make it work for me. This code works but I don't exactly know how to get it to wrap multiple commands.

在 ZSH 中,等效代码不起作用,我无法弄清楚如何使其对我有用。这段代码有效,但我不知道如何让它包装多个命令。

{ time echo "something" } 2>&1

I know I can create a new script and put the commands in there then time the execution properly, but is there a way to do it either using functions or a similar method to the bash above?

我知道我可以创建一个新脚本并将命令放在那里然后正确执行时间,但是有没有办法使用函数或与上面的 bash 类似的方法来做到这一点?

回答by Zsolt Botykai

Try the following instead:

请尝试以下操作:

{ time ( echo hello ; sleep 10s;  echo hola ; ) } 2>&1 

回答by Pablo Castellazzi

If you want to profile your code you have a few alternatives:

如果你想分析你的代码,你有几个选择:

  • Time subshell execution like:

    time ( commands ... )

  • Use REPORTTIME to check for slow commands:

    export REPORTTIME=3 # display commands with execution time >= 3 seconds

  • setop xtraceas explained here

  • The zprofmodule

  • 时间子shell执行如:

    time ( commands ... )

  • 使用 REPORTTIME 检查慢命令:

    export REPORTTIME=3 # display commands with execution time >= 3 seconds

  • setop xtrace为解释在这里

  • zprof模块

回答by eran

Try replace { with ( ? I think this should help

尝试将 { 替换为 ( ?我认为这应该会有所帮助

回答by Jens

You can also use the timesPOSIX shell builtin in conjunction with functions. It will report the user and system time used by the shell and its children. See http://pubs.opengroup.org/onlinepubs/009695399/utilities/times.html

您还可以将times内置的POSIX shell 与函数结合使用。它将报告 shell 及其子进程使用的用户和系统时间。请参阅 http://pubs.opengroup.org/onlinepubs/009695399/utilities/times.html

Example:

例子:

somefunc() {
    code you want to time here
    times
}

The reason for using a shell function is that it creates a new shell context, at the start of which timesis all zeros (try it). Otherwise the result contains the contribution of the current shell as well. If that is what you want, forget about the function and put timeslast in your script.

使用 shell 函数的原因是它创建了一个新的 shell 上下文,在它的开头times全为零(试试看)。否则,结果也包含当前 shell 的贡献。如果这是您想要的,请忘记该功能并将其放在times脚本的最后。