2015年12月9日 星期三

[Linux 常見問題] Shell - How to calculate time difference in bash script?

Source From Here
Question
I print the start and end time using date +"%T", which results in something like:
10:33:56
10:36:10

How could I calculate and print the difference between these two? I would like to get something like:
2m 14s

How-To
I guess the easiest solution would be to obtain the time as the number of seconds since the Unix epoch, and then subtract them, doing the time arithmetic before displaying.

The -u parameter instructs date to return the time in UTC. This is needed in order to keep the timeline continuous : without that option, the calculation of diff could return an incorrect value if a DST transition happened between the two calls to date. This parameter is required by POSIX, so I bet it's widely supported across various Unices.
- test.sh
  1. #!/bin/sh  
  2. date1=$(date -u +"%s")  
  3. sleep 5  
  4. date2=$(date -u +"%s")  
  5. diff=$(($date2-$date1))  
  6. echo "$(($diff / 60)) minutes and $(($diff % 60)) seconds elapsed."  
Execution result:
# ./test.sh
0 minutes and 5 seconds elapsed.


沒有留言:

張貼留言

[ Java 文章收集 ] 局部敏感哈希 (Locality-Sensitive Hashing, LSH) 方法介紹

Source From  Here   Preface   本文主要介紹一種用於海量高維數據的近似最近鄰快速查找技術—— 局部敏感哈希  ( Locality-Sensitive Hashing, LSH ),內容包括了 LSH 的原理、LSH 哈希函數集、以及 LSH 的一...