我需要一个函数或方法来在几秒钟内获得 UNIX 纪元,就像我在 PHP 中使用 time 函数一样。
我找不到任何方法,除了 ctime 中的 time() 似乎只输出格式化的日期,或者具有秒数但似乎总是 100 万的倍数的 clock() 函数,没有任何分辨率。
我想测量程序的执行时间,我只想计算开始和结束之间的差异;C++ 程序员将如何做到这一点?
编辑: time() 和 difftime 只允许以秒为单位的分辨率,而不是 ms 或任何东西。
time()应该可以正常工作,使用difftime计算时间差。如果您需要更好的解决方案,请使用gettimeofday。
此外,重复:计算 C 程序中经过的时间(以毫秒为单位)
如果您想分析 get,我建议使用getrusage。这将允许您跟踪 CPU 时间而不是挂钟时间:
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
ru.ru_utime.tv_sec; // seconds of user CPU time
ru.ru_utime.tv_usec; // microseconds of user CPU time
ru.ru_stime.tv_sec; // seconds of system CPU time
ru.ru_stime.tv_usec; // microseconds of system CPU time
这段代码应该适合你。
time_t epoch = time(0);
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t time = time(0);
cout<<time<<endl;
system("pause");
return 0;
}
如果您有任何疑问,请随时在下面发表评论。