我正在为 Nushell 编写自定义执行时间格式化程序函数,并且遇到需要在需要时显示值的需求。首先看一下代码:
def tooktime_fmt [exect: string] {
let execi = ($exect | into int)
if $execi < 1000 {
return ([$exect, "ms"] | str join)
} else if $execi < 60000 {
let s_passed = ($execi / 1000 | into int)
let ms_rem = ($execi - ($s_passed * 1000))
return ([$s_passed, "s", $ms_rem, "ms"] | str join)
} else if $execi < 3600000 {
let s_passed = ($execi / 1000 | into int)
let m_passed = ($s_passed / 60 | into int)
let ms_rem = ($execi - ($s_passed * 1000))
let s_rem = ($s_passed - $m_passed * 60)
return ([$m_passed, "m", $s_rem, "s", $ms_rem, "ms"] | str join)
} else {
let s_passed = ($execi / 1000 | into int)
let m_passed = ($s_passed / 60 | into int)
let h_passed = ($s_passed / 3600 | into int)
let ms_rem = ($execi - ($s_passed * 1000))
let s_rem = ($s_passed - $m_passed * 60)
let m_rem = ($m_passed - $h_passed * 60)
return ([$h_passed, "h", $m_rem, "m", $s_rem, "s", $ms_rem, "ms"] | str join)
}
}
它很有魅力,但是,我担心内存和状况检查。
我本可以做什么:
s_passed
、m_passed
、h_passed
、ms_rem
、s_rem
、m_rem
;if not 0
的补充函数。对于任何想知道的人:我从
exect
得到 $env.CMD_DURATION_MS
,因此在转换时检查错误感觉没有必要。
如何优化您的代码如下。
def tooktime_fmt(exec_time: str) -> str:
exec_time_ms = int(exec_time)
if exec_time_ms < 1000:
return f"{exec_time_ms} ms"
elif exec_time_ms < 60000:
seconds = exec_time_ms // 1000
milliseconds = exec_time_ms % 1000
return f"{seconds}s {milliseconds}ms"
elif exec_time_ms < 3600000:
minutes = exec_time_ms // 60000
seconds = (exec_time_ms % 60000) // 1000
milliseconds = exec_time_ms % 1000
return f"{minutes}m {seconds}s {milliseconds}ms"
else:
hours = exec_time_ms // 3600000
minutes = (exec_time_ms % 3600000) // 60000
seconds = (exec_time_ms % 60000) // 1000
milliseconds = exec_time_ms % 1000
return f"{hours}h {minutes}m {seconds}s {milliseconds}ms"
请尝试这个。 最美好的祝愿。