c和c++在windows下获取时间和计算时间差的方法总结[归类].pdfVIP

  • 0
  • 0
  • 约6.36千字
  • 约 5页
  • 2021-10-13 发布于福建
  • 举报

c和c++在windows下获取时间和计算时间差的方法总结[归类].pdf

c/c++ 在 windows 下获取时间和计算时间差的几种方法总结 一、标准 C 和 C++ 都可用 1 、获取时间用 time_t time ( time_t * timer ) ,计算时间差使用 double difftime( time_t timer1, time_t timer0 ) 。 精确到秒。 测试程序如下: 1. #include time.h 2. #include stdio.h 3. int main() 4. { 5. time_t start ,end ; 6. double cost; 7. time(start); 8. sleep(1); 9. time(end); 10. cost=difftime(end,start); 11. printf( %f\n ,cost); 12. return 0; 13. } 本程序在 fedora9 测试通过。 关于代码中的 sleep 函数,需要注意的是: 1 )在 windows 下,为 Sleep() 函数,且需包含 windows.h 2 )关于 sleep 中的数,在 Windows 和 Linux 下 1000 代表的含义并不相同, Windows 下的表示 1000 毫秒,也就是 1 秒钟; Linux 下表示 1000 秒, Linux 下使用毫秒级别的 函数可以使用 usleep 。 2 、clock_t clock() clock() 获取的是计算机启动后的时间间隔 ,得到的是 CPU 时间 ,精确到 1/CLOCKS_PER_SEC 秒。 测试程序如下: 1. #include time.h 2. #include stdio.h 3. int main() 4. { 5. double start,end,cost; 6. start=clock(); 7. sleep(1); 8. end=clock(); 9. cost=end-start; 10. printf( %f\n ,cost); 11. return 0; 12. } 二、 C++ 中(此处针对 windows 环境,标准 c 中则 linux 和 windows 都可以) 1 、GetTickCount() 调用函数需包含 windows.h 。得到的是系统运行的时间 精确到毫秒, 测试程序如下: 1. #include iostream 2. #include windows.h 3. using namespace std; 4. int main() 5. { 6. double start = GetTickCount(); 7. Sleep(1000); 8. double end=GetTickCount(); 9. cout GetTickCount: end-s

文档评论(0)

1亿VIP精品文档

相关文档