계산하다시간존재하다나노초아래에GNU/Linux, 사용세게 때리다.

계산하다시간존재하다나노초아래에GNU/Linux, 사용세게 때리다.

내 프로그램이 완료되는 데 걸리는 시간(경과 시간이라고도 함)을 구하려고 하므로 일반 time.

이를 통해 사용자, 시스템, 전체라는 3가지 측정값을 얻었습니다. 괜찮습니다. 하지만 제가 관심을 갖고 있는 사용자 시간은 소수점 이하 두 자리까지에 불과하고 더 많은 시간이 필요하다는 것을 알게 되었습니다. 시간 명령에서 소수점 이하 자릿수를 더 많이 얻을 수 있는 방법이 있나요?

예: time ./myCProgram
출력: 0.17s 사용자 1.21s 시스템 130% CPU 0.187 총

원하는 출력: 0.17000s 사용자 1.21s 시스템 130% CPU 0.187 총 (또는 더 많은 소수 자릿수)

답변1

원하는 것이 경과 시간뿐이라면 zsh 또는 ksh93을 사용하십시오.

$ typeset -F SECONDS=0; sleep 1; print "$SECONDS"
1.0012850761

이제 이 정밀도가 의미가 있는지 여부는 또 다른 문제입니다.

답변2

계산하다시간존재하다나노초아래에GNU/Linux, 사용.

경고하다이 문서는 거기에서 논의된 새로운 좋은 방법으로 인해 더 이상 사용되지 않습니다.bash 분석(답변 3개)그리고 가득 차있는사용할 수 있다 소스 파일은 다음과 같습니다.Elap-bash V3

신뢰할 수 있는 값을 검색하는 방법

1초보다 더 세부적인 시간을 요청하는 방법이 있습니다.

첫째, 최고는 아니지만: 1/100초

1/100초에 대해서는 다음을 간단히 참조할 수 있습니다 /proc/uptime.

sed 's/ .*$//' /proc/uptime 
276440.58

이것시간 오프셋실제 UTC 시간 계산을 위한 콘텐츠 추가는 다음 방법 중 하나로 얻을 수 있습니다.

ps ho lstart 1 | date -f - +%s
1357193821

또는

date +%s.%N-$(sed 's/ .*$//' /proc/uptime ) | bc -l
1357193821.088187101

오프셋은 정적이므로 스크립트 시작 부분에서 값을 한 번만 계산할 수 있습니다.

1/1000000000초, proc항목만 사용:

계산에 사용나노초, 및 을 모두 포함하는 proc entry이름의 이 있습니다 ./proc/timer_listuptimeoffset

sed < /proc/timer_list -ne '/now at/p;/offset/{p;q}'
now at 276350507668586 nsecs
  .offset:     1357193821075753443 nsecs

그래서 이거

echo $(($(sed < /proc/timer_list -ne '
    /^now at/{s/now at \([0-9]*\) ns.*$/\1/;H};
    /offset/{s/^.*: *\([0-9]*\) ns.*$/\1/;G;s/\n\+/+/;p;q}'))) 
1357470173543424035

~이다정수수량나노초과거로부터 1970-1-1 00:00:00 UTC.

더 낮은 정수를 계산하는 데 사용됩니다., proc 파일을 사용하고 구문 bc분석할 필요가 없습니다 .mapfile배쉬 내장:

# first, some static variables (with fork, but only 1 time, at begin;):
nowAtLine=$(($(sed -ne < /proc/timer_list '/now at/{=;q}')-1))
offset=$(sed -ne < /proc/timer_list '
    /offset/{s/^.*: *\([0-9]*\) n.*$/\1/p;q}')

# than this will be a lot quicker than a fork:
mapfile -n 1 -s $nowAtLine timerList </proc/timer_list &&
    timerList=($timerList) &&
    echo $((${timerList[2]}+offset))
1357470173543424035

1/1000000000초, date바이너리 도구 사용:

마지막으로, 존재하지 않는 경우 bash 세션에 머물면서 읽는 것보다 시간이 더 걸린다는 date것을 기억할 수 있습니다.forkproc files

date +%s%N
1357470074808968375

elap.bash기능

이를 바탕으로 글을 썼습니다elap bash 기능, 두 개의 카운터가 있습니다. 각 통화마다 하나씩, 각 통화마다 하나씩 overall duration.

용법:

우선, 이것은기능,하나도 아니야스크립트. source이를 사용하려면 현재 bash 세션에 있어야 합니다 .

. elap.bash
문법:
elap [ [ -r | -R ] | [ -n ] [ -t | -T ] [<simple text report>] ]
    -r reset first counter only, don't output anything, like -R...
    -R reset both counters, (both -r and -R must by unique argument)
    -n don't reset any counter (just print)
    -t print both counters (reset first counter)
    -T print and reset

사용하기 전에 두 카운터를 모두 재설정하십시오.

elap -R
find /usr/bin >/dev/null
elap browsing /usr/bin

     0.025389543 browsing /usr/bin

따라서 스크립트에 몇 가지 태그를 추가할 수 있습니다.

#!/bin/bash
. elap.bash
  elap -R
tar -cf /tmp/test.tar -C / bin
  elap making a tarball of $(stat -c %s /tmp/test.tar) bytes
gzip /tmp/test.tar
  elap compressing them to $(stat -c %s /tmp/test.tar.gz) bytes
scp /tmp/test.tar.gz [email protected]:backups/
  elap sending file to backup server
rm /tmp/test.tar.gz
  elap removing compressed tarball
elap -t total duration

     0.043223957 making a tarball of 5877760 bytes
     0.667249628 compressing them to 2742537 bytes
test.tar.gz                                  100% 2678KB 2.6MB/s 00:00
     0.380779818 sending file to backup server
     0.010262259 removing compressed tarball
     0.003566335      1.105081997 total duration

trap debug다음 용도 로 사용됩니다 .단계별로

스위치를 사용하거나 사용하지 않고 단계적으로 사용하며 -t스크립트 변경 횟수를 줄입니다(스크립트 상단에 4줄, 하단에 1줄 추가).trap debug

함정으로디버그일어날 것이다앞으로 $BASH_COMMAND실행 시 올바른 인쇄를 위해 변수의 내용을 $BASH_LAST변수에 저장하고 추가해야 합니다.가짜명령은 스크립트 하단에 있습니다.

#!/bin/bash

. elap.bash
elap -R
export BASH_LAST=Starting
trap 'elap -t $BASH_LAST;BASH_LAST=$BASH_COMMAND' debug 

tar -cf /tmp/test.tar -C / bin
gzip /tmp/test.tar
scp /tmp/test.tar.gz [email protected]:backups/
rm /tmp/test.tar.gz

exit $?

exit $?이 명령은 통계를 덤프하는 데 필요합니다.뒤쪽에마지막 rm명령입니다.

     0.001011086      0.001011086 Starting
     0.045175969      0.046187055 tar -cf /tmp/test.tar -C / bin
     0.651394209      0.697581264 gzip /tmp/test.tar
test.tar.gz                                  100% 2678KB 2.6MB/s 00:00
     0.374499354      1.072080618 scp /tmp/test.tar.gz [email protected]:backups/
     0.007160101      1.079240719 rm /tmp/test.tar.gz

함수 소스 코드

uptime1/100초 단위를 사용하는 대신 포크를 사용하려는 경우 date +%s%N섹션을 잘라내거나 재정렬할 수 있습니다.

#
# Bash source file for fine elapsed time reporting
# based on /proc/timer_list, display elapsed time in nanosecs
# or /proc/uptime if timer_list not present, for 100th of secs.
# if none of them if present, fall back to *fork* `date +%s%N`.
#
# (C) 2011-2012 Felix Hauri - [email protected]
# Licensed under terms of LGPL v3. www.gnu.org

# Usage:
#   load script into bash using ``source elap.bash''
#
# Syntaxe: elap [ [ -r | -R ] | [ -n ] [ -t | -T ] [<simple text report>] ]
#   -r reset first counter only, don't output anything, like -R...
#   -R reset both counters, (both -r and -R must by unique argument)
#   -n don't reset any counter (just print)
#   -t print both counters (reset first counter)
#   -T print and reset
#
# nota: using ``-n'' in combinaison with any of ``-r'' or ``-R'' is buggy.

export _elaP_now _elaP_last _elaP_elap _elaP_last2 _elaP_dec

if [ -r /proc/timer_list ] ;then
    _elaP_file=/proc/timer_list
    _elaP_dec=9
    _elaP_field=2
    mapfile < $_elaP_file _elaP_now
    _elaP_line=0
    while [ "${_elaP_now[_elaP_line]}" == \
    "${_elaP_now[_elaP_line]#*now at}" ] ;do
    ((_elaP_line++))
    done
    eval 'function elap_getNow() {
     mapfile -n 1 -s '$_elaP_line' <'$_elaP_file' _elaP_now
         _elaP_now=($_elaP_now)
         _elaP_now=${_elaP_now[_elaP_field]}
         }'
else
    #      --- To be removed for nanoseconds only
    if [ -r /proc/uptime ] ;then
    _elaP_dec=2
    function elap_getNow() {
        read -a _elaP_now </proc/uptime _elaP_now
            _elaP_now=${_elaP_now//./}
    }
    else # --- End of part to be removed for ns only.
    _elaP_dec=9
    function elap_getNow() { _elaP_now=$(date +%s%N) ;}
    fi   # --- Remove this line too for ns only.
fi

export -f elap_getNow

elap() {
    local _Z9=000000000
    local _elaP_setLast=true
    [ "$1" == "-n" ] && shift && _elaP_setLast=false
    [ "$2" == "-n" ] && set -- $1 ${@:3} && _elaP_setLast=false

    elap_getNow

    _elaP_elap=$((_elaP_now - _elaP_last))
    [ ${#_elaP_elap} -lt $_elaP_dec ] && \
    _elaP_elap=${_Z9:0:_elaP_dec-${#_elaP_elap}}$_elaP_elap
    [ "${*}" == "-R" ] &&  _elaP_last2=$_elaP_now || \
    [ "${*}" == "-r" ] || if [ "$1" == "-t" ] || [ "$1" == "-T" ] ;then
    local _elaP_setLast2=false
    [ "$1" == "-T" ] && _elaP_setLast2=true
    shift
            _elaP_elap2=$((_elaP_now - _elaP_last2))
    [ ${#_elaP_elap2} -lt $_elaP_dec ] && \
        _elaP_elap2="${_Z9:0:_elaP_dec-${#_elaP_elap2}}$_elaP_elap2"
        printf "%6d.%s %6d.%s %s\n" \
        "${_elaP_elap:0:${#_elaP_elap}-$_elaP_dec}" \
        "${_elaP_elap:${#_elaP_elap}-_elaP_dec}" \
        "${_elaP_elap2:0:${#_elaP_elap2}-$_elaP_dec}" \
        "${_elaP_elap2:${#_elaP_elap2}-_elaP_dec}"      "${*}"
    $_elaP_setLast2 && _elaP_last2=$_elaP_now
    else
        printf "%6d.%s %s\n" \
        "${_elaP_elap:0:${#_elaP_elap}-$_elaP_dec}" \
        "${_elaP_elap:${#_elaP_elap}-_elaP_dec}"        "${*}"
    fi
    $_elaP_setLast && _elaP_last=$_elaP_now
}

export -f elap

관련 정보