C++获得毫秒级的时间差(支持Windows 和 Linux)

举报
墨理学AI 发表于 2022/01/13 23:06:05 2022/01/13
【摘要】 fatal error: windows.h: No such file or directory 我这里Windows 里面引用了 #include <windows.h> ,使用下面的方法...

fatal error: windows.h: No such file or directory
我这里Windows 里面引用了 #include <windows.h> ,使用下面的方法测量函数运行时间

#include <iostream>
#include <windows.h>
using namespace std;
void timeTest()
{
	for(int i =0;i<1000;i++)
		cout<<i<<endl; 
}

int main()
{
	long start_time = GetTickCount();
  	timeTest();
	long end_time = GetTickCount();
    cout << "Running Time:" << end_time - start_time << "ms" << endl;
}
  
 

代码迁移到Linux下报错,找不到 windows.h。
于是选择使用Linux下的另外一种测量函数运行时间的方法,使用 #include <time.h>头文件,代码如下:

#include <iostream>
#include <time.h>
using namespace std;

void timeTest()
{
	for(int i =0;i<1000;i++)
		cout<<i<<endl; 
}

int main()
{
	clock_t start, ends;
	start = clock();
 	timeTest();
	ends = clock();
	cout << "Running Time: " << ends - start<<" ms" << endl;
}
  
 

以上两个方法在Windows下也都是准确的,然而到了Linux服务器下就不够精确了,于是请看下面的方法:

最终准确的函数运行时间度量方法——推荐使用: 而且下面这种方法的效率要高很多–个人实测

C++的<time.h>头文件中有time和clock可以用来计算时间,但是“#include < chrono >”中提供了更加精确的统计时间的方法。
下面的代码支持Windows 和 Linux,但是要求编译器必须支持C++11

#include <iostream>
#include <chrono>
using namespace std;
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;

void timeTest()
{
	for(int i =0;i<1000;i++)
		cout<<i<<endl; 
}

int main()
{
    high_resolution_clock::time_point beginTime = high_resolution_clock::now();
    
  	timeTest();
  
    high_resolution_clock::time_point endTime = high_resolution_clock::now();
    milliseconds timeInterval = std::chrono::duration_cast<milliseconds>(endTime - beginTime);
    cout << "Running Time:" << timeInterval.count()  << "ms" << endl;
}
  
 

最终方法感谢原作者:TheOneGIS

文章来源: positive.blog.csdn.net,作者:墨理学AI,版权归原作者所有,如需转载,请联系作者。

原文链接:positive.blog.csdn.net/article/details/84136133

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。