我對如何操作從clock_gettime 獲得的值的細節有一些疑問。我想計算一個可執行檔案/命令的總運行時間。
我希望以(例如 3.475s)的格式列印實時資訊,我快完成了,但我很確定它不會以我想要的格式回傳。我怎么能這樣?
struct timespec tsstart, tsend;
clock_gettime(CLOCK_MONOTONIC, &tsstart);
//execuatble/command executes and finishes
clock_gettime(CLOCK_MONOTONIC, &tsend);
long long realtime = (tsend.tv_sec-tsstart.tv_sec)*1000000LL tsend.tv_usec-tsstart.tv_usec;
printf("real: %.3lds, ", realtime);
每當我嘗試運行它時,在短時間內(即 <10 秒),我得到的只是一個輸出
35273s
如何將輸出格式更改為 3d.p. 我需要的精度?
uj5u.com熱心網友回復:
struct timespec tsstart, tsend;
clock_gettime(CLOCK_MONOTONIC, &tsstart);
//execuatble/command executes and finishes
clock_gettime(CLOCK_MONOTONIC, &tsend);
float realtime = (tsend.tv_sec-tsstart.tv_sec) (tsend.tv_nsec-tsstart.tv_nsec)/1000000000.0;
printf("real: %.3fs, ", realtime);
uj5u.com熱心網友回復:
將縮放long long整數 ( *1000000LL) 更改為 x.xxxxxx 輸出
printf("%s%lld.lld",
realtime < 0 ? "-" : "",
llabs(realtime/1000000),
llabs(realtime%1000000));
棘手的案件包括realtime在中值[-999999 ... -1]。當然,這些值不是時間減法所期望的。
如果我們假設 realtime >= 0,那么
printf("%lld.lld",
realtime/1000000, realtime%1000000);
拋低 3 位數字:
// Form rounded quotient of milliseconds
long long ms = realtime/1000 (realtime%1000 >= 500);
printf("%lld.lld", ms/1000, ms%1000);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/319092.html
上一篇:從網站地理封鎖用戶的最簡單方法?
