반응형
1)
clock_t start = clock();
clock_t init_time = clock() - start;
2)
clock_gettime(CLOCK_MONOTONIC, &start);
clock_gettime(CLOCK_MONOTONIC, &end);
double time_taken = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000000.0;
Q1) What is difference between those two code.
The first code block measures the time using the clock function from the time.h library. It measures the time in clock cycles, which is the number of processor clock cycles executed. This method of timing is not very accurate and can vary depending on the processor and system.
The second code block uses the clock_gettime function from the time.h and sys/time.h libraries. It measures the time in seconds and nanoseconds and provides a more accurate measurement of the time taken for a certain operation. The CLOCK_MONOTONIC flag is used to specify that the monotonic clock should be used. The monotonic clock is a clock that cannot be set or adjusted and represents the time elapsed since some unspecified starting point. The result is stored in a timespec struct, which has two fields: tv_sec for seconds and tv_nsec for nanoseconds. The difference between the two timespec structs is calculated and then converted to milliseconds.
Q2) I used second code and got a negative time value. how can i fix it?
It looks like the second code is correct for measuring the time taken for a specific operation, but if you are getting a negative time value, it might be because end.tv_sec is smaller than start.tv_sec or end.tv_nsec is smaller than start.tv_nsec.
If this is the case, try using timespec_get instead of clock_gettime, as it provides better compatibility across different platforms. Here is an example:
struct timespec start, end;
timespec_get(&start, TIME_UTC);
// Do the operation you want to time here
timespec_get(&end, TIME_UTC);
double time_taken = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000000000.0;
The difference in the code is that timespec_get sets the timespec value to the current time in UTC, whereas clock_gettime requires you to pass the clock id as an argument. Additionally, the calculation for time taken has been changed to convert nanoseconds to seconds.
반응형
'Programming > C' 카테고리의 다른 글
| The malloc function can fail to allocate memory in several cases (0) | 2023.02.09 |
|---|
댓글