我试图使用时间()来测量我的程序的各个点。
我不明白的是为什么前后的值是一样的?我知道这不是分析我的程序的最佳方式,我只是想看看需要多长时间。
printf("**MyProgram::before time= %ld\n", time(NULL));
doSomthing();
doSomthingLong();
printf("**MyProgram::after time= %ld\n", time(NULL));
我试过:
struct timeval diff, startTV, endTV;
gettimeofday(&startTV, NULL);
doSomething();
doSomethingLong();
gettimeofday(&endTV, NULL);
timersub(&endTV, &startTV, &diff);
printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec);
我如何读取**时间花费= 0 26339的结果?这是否意味着26339纳秒= 26.3毫秒?
**时间= 4 45025,这是否意味着4秒25毫秒?
回答OP的三个具体问题。
“我不明白的是,为什么之前和之后的数值是一样的?”
第一个问题和示例代码显示time()的分辨率为1秒,因此答案必须是两个函数在1秒内执行。但如果两个计时器标记跨越了一秒的边界,它偶尔会(显然是不合逻辑的)通知1秒。
下一个示例使用gettimeofday()填充该结构体
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
第二个问题是:“我如何读取**时间= 0 26339的结果?这是否意味着26339纳秒= 26.3毫秒?”
我的第二个答案是所花费的时间是0秒和26339微秒,即0.026339秒,这证实了第一个示例在不到1秒的时间内执行。
第三个问题是:“**时间= 4 45025,这是否意味着4秒25毫秒?”
我的第三个答案是所用的时间是4秒和45025微秒,即4.045025秒,这表明OP改变了他之前计时的两个函数执行的任务。
下面是一个简单的类,它将在指定的持续时间单位内打印它进入和离开作用域之间的持续时间:
#include <chrono>
#include <iostream>
template <typename T>
class Benchmark
{
public:
Benchmark(std::string name) : start(std::chrono::steady_clock::now()), name(name) {}
~Benchmark()
{
auto end = std::chrono::steady_clock::now();
T duration = std::chrono::duration_cast<T>(end - start);
std::cout << "Bench \"" << name << "\" took: " << duration.count() << " units" << std::endl;
}
private:
std::string name;
std::chrono::time_point<std::chrono::steady_clock> start;
};
int main()
{
Benchmark<std::chrono::nanoseconds> bench("for loop");
for(int i = 0; i < 1001000; i++){}
}
使用示例:
int main()
{
Benchmark<std::chrono::nanoseconds> bench("for loop");
for(int i = 0; i < 100000; i++){}
}
输出:
Bench "for loop" took: 230656 units