C++ 记录代码所用的时间
我使用以下函数来查找代码所用的时间C++ 记录代码所用的时间,c++,c++11,C++,C++11,我使用以下函数来查找代码所用的时间 #include <sys/time.h> struct timeval start, end; gettimeofday(&start,NULL); //mycode gettimeofday(&end,NULL); cout<<" time taken by my code: "<<((end.tv_sec - start.tv_sec) * 1000000 + end
#include <sys/time.h>
struct timeval start, end;
gettimeofday(&start,NULL);
//mycode
gettimeofday(&end,NULL);
cout<<" time taken by my code: "<<((end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec ) / 1000.0<<" msec"<<endl;
#包括
结构timeval开始、结束;
gettimeofday(&start,NULL);
//麦可德
gettimeofday(&end,NULL);
cout我最好的猜测是系统上的time\u t
(类型为tv\u sec
)是有符号的32位,并且(end.tv\u sec-start.tv\u sec)*1000000溢出
您可以通过确保此计算不使用32位算术来测试该理论:
(end.tv_sec - start.tv_sec) * 1000000LL
尽管如此,我还是建议使用C++11
库:
#include <chrono>
auto t0 = std::chrono::system_clock::now();
//mycode
auto t1 = std::chrono::system_clock::now();
using milliseconds = std::chrono::duration<double, std::milli>;
milliseconds ms = t1 - t0;
std::cout << " time taken by my code: " << ms.count() << '\n';
#包括
自动t0=std::chrono::system_clock::now();
//麦可德
自动t1=std::chrono::system_clock::now();
使用毫秒=std::chrono::duration;
毫秒ms=t1-t0;
std::cout您在哪个平台上执行此操作?如果是Linux/Unix,最简单的非侵入性赌注就是从命令行使用time命令。您运行的代码是否为单线程?time.h中的一些函数(如clock()等)返回每个内核的刻度数,这可能是您想要的,也可能不是您想要的。chrono中较新的东西可能没有你想的那么精确(前一段时间,我试图用chrono测量纳秒级的时间间隔,但当时我得到的最低时间间隔是300ns,比我希望的要精确得多)。基准测试过程的这一部分可能有助于你达到以下目的:
#include<time.h>
#include<cstdlib>
...
...
float begin = (float)clock()/CLOCKS_PER_SEC;
...
//do your bench-marking stuffs
...
float end = (float)clock()/CLOCKS_PER_SEC;
float totalTime = end - begin;
cout<<"Time Req in the stuffs: "<<totalTime<<endl;
#包括
#包括
...
...
浮点开始=(浮点)时钟()/每秒时钟;
...
//做你的标杆工作
...
浮点结束=(浮点)时钟()/每秒时钟;
浮动总时间=结束-开始;
cout如果您在linux上,并且您想要计时的代码主要是程序本身,那么您可以通过将其作为参数传递给time命令来计时程序,并查看“已用时间”行
/usr/bin/time -v <your program's executable>
你应该看看新的c++11库chrono,而不是使用时间。h.@ViktorSehr当然……你能给我一些例子说明如何使用ChronooOverflow是可能的罪魁祸首吗?根据time\t
是有符号的还是无符号的,它大约每35或71分钟包装一次。尽管如此,1213ms仍然可疑地接近于零,因此可能存在其他问题。chrono是否不会出现溢出?@JannatArora:回答中提到。
/usr/bin/time -v sleep 3 .../home/aakashah/workspace/head/src/GroverStorageCommon
Command being timed: "sleep 3"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 0%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:03.00
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 2176
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 165
Voluntary context switches: 2
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0