C++中获取当前时间有四种方法:time() 函数:返回当前时间的秒数(自纪元以来的秒数)。gettimeofday() 函数:返回当前时间和微秒数。clock() 函数:返回进程开始执行以来的CPU时间(以时钟周期为单位)。Boost 库中的date_time 库:提供了更多精确和灵活的时间处理功能。

C++中获取当前时间
在C++中,获取当前时间有以下几种方法:
1. time() 函数
time() 函数返回当前时间的秒数(自纪元以来的秒数)。
立即学习“C++免费学习笔记(深入)”;
<code class="cpp">#include <time.h>
int main() {
time_t current_time = time(NULL);
printf("当前时间(秒数):%ld\n", current_time);
return 0;
}</code>2. gettimeofday() 函数
gettimeofday() 函数返回当前时间和微秒数。
<code class="cpp">#include <sys/time.h>
int main() {
struct timeval current_time;
gettimeofday(¤t_time, NULL);
printf("当前时间(秒数):%ld\n", current_time.tv_sec);
printf("当前时间(微秒数):%ld\n", current_time.tv_usec);
return 0;
}</code>3. clock() 函数
clock() 函数返回进程开始执行以来的CPU时间(以时钟周期为单位)。
<code class="cpp">#include <time.h>
int main() {
clock_t start_time = clock();
// 执行一些操作
clock_t end_time = clock();
double elapsed_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;
printf("已用时间:%.2fs\n", elapsed_time);
return 0;
}</code>4. Boost 库中的date_time 库
Boost 库中的date_time 库提供了更多精确和灵活的时间处理功能。
<code class="cpp">#include <boost/date_time/posix_time/posix_time.hpp>
int main() {
boost::posix_time::ptime current_time = boost::posix_time::microsec_clock::local_time();
std::cout << "当前时间(微秒):" << current_time << std::endl;
return 0;
}</code>以上就是c++++怎么获取当前时间的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号