I'm having a bit of an issue with the specifics of how to manipulate the values obtained from clock_gettime. Im looking to calculate the total running time of an executable/command.
I'm looking to print out the realtime in the format of (eg. 3.475s) I'm almost done but am pretty sure that it wont return in the format I want. How could I do so?
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);
Whenever I try running this, for a short period (ie. <10s), all I get is an output along the lines of
35273s
How could I change the formatting of the output to the 3d.p. precision I need ?
CodePudding user response:
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);
CodePudding user response:
To change scaled long long
integer (*1000000LL
) to a x.xxxxxx output
printf("%s%lld.lld",
realtime < 0 ? "-" : "",
llabs(realtime/1000000),
llabs(realtime%1000000));
Tricky cases include realtime
values in the the [-999999 ... -1]
. Of course these values are not expected with the time subtraction.
If we assume realtime >= 0
, then
printf("%lld.lld",
realtime/1000000, realtime%1000000);
To toss the lower 3 digits:
// Form rounded quotient of milliseconds
long long ms = realtime/1000 (realtime%1000 >= 500);
printf("%lld.lld", ms/1000, ms%1000);