简体   繁体   中英

c++ time.h, clock_gettime(), semantic error, how to link real-time library in Eclipse?

I have some problem using the clock_gettime() function.

#include <iostream>
#include <time.h>

timespec timer_start;
timespec timer_end;

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &timer_start);
// sleep for 5 seconds
boost::this_thread::sleep(boost::posix_time::milliseconds(5000));
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &timer_end);

std::cout << (timer_end.tv_sec - timer_start.tv_sec) << ":" << (timer_end.tv_nsec - timer_start.tv_nsec) << std::endl;

The output I get is this

0:6934599

It seems that the timer only elapsed 693 milliseconds or so.

I compile the program with g++ -lrt on Linux gnu gcc 4.6. I also received a Semantic Error, says Symbol 'CLOCK_PROCESS_CPUTIME_ID' could not be resolved

Thanks.

Leaving aside the impossibility of running a program that fails to compile, sleeping is typically a system call: a kernel function is called, the kernel sends the thread to sleep, schedules other threads and processes to run (or the CPU to enter a power saving mode) and wakes the original thread up again at the requested time. During this time, the sleeping thread will not consume CPU time. The (real) time that elapses is typically referred to as wall time .

Contrast this to a live wait of a while loop in your code that repeatedly checks the clock and only terminates after 5 seconds have elapsed. This kind of wait will rack up CPU time it takes away from other processes.

Note also that 6934599 nanoseconds are about 6.93 milliseconds, not 693.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM