阅读量:67
- 计算程序运行时间:可以使用timeval记录程序开始和结束时的时间戳,然后计算两者之差来获取程序运行时间。
#include
#include
int main() {
struct timeval start, end;
gettimeofday(&start, NULL);
// Your code here
gettimeofday(&end, NULL);
long seconds = end.tv_sec - start.tv_sec;
long micros = end.tv_usec - start.tv_usec;
double elapsed = seconds + micros/1000000.0;
std::cout << "Program executed in " << elapsed class="hljs-string">" seconds." << std class="hljs-keyword">return 0;
}
- 实现定时器功能:可以使用timeval来设置定时器,当时间达到指定值时触发某种操作。
#include
#include
#include
void timerCallback() {
std::cout << "Timer expired!" << std class="hljs-function">int main() {
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
select(0, NULL, NULL, NULL, &timeout);
timerCallback();
return 0;
}
- 计算两个时间点之间的时间差:可以使用timeval来记录两个时间点,然后计算它们之间的时间差。
#include
#include
int main() {
struct timeval start, end;
gettimeofday(&start, NULL);
// Some operations
gettimeofday(&end, NULL);
long seconds = end.tv_sec - start.tv_sec;
long micros = end.tv_usec - start.tv_usec;
double elapsed = seconds + micros/1000000.0;
std::cout << "The time difference is " << elapsed class="hljs-string">" seconds." << std class="hljs-keyword">return 0;
}
这些是一些C++中timeval的典型用法示例,可以根据具体的需求进行修改和扩展。