我试图使用时间()来测量我的程序的各个点。
我不明白的是为什么前后的值是一样的?我知道这不是分析我的程序的最佳方式,我只是想看看需要多长时间。
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毫秒?
下面是一个简单的类,它将在指定的持续时间单位内打印它进入和离开作用域之间的持续时间:
#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