轻松测量经过的时间 [英] Easily measure elapsed time

查看:24
本文介绍了轻松测量经过的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 time() 来测量各个点我的程序.

I am trying to use time() to measure various points of my program.

我不明白的是为什么之前和之后的值是一样的?我知道这不是描述我的程序的最佳方式,我只是想看看某件事需要多长时间.

What I don't understand is why the values in the before and after are the same? I understand this is not the best way to profile my program, I just want to see how long something take.

printf("**MyProgram::before time= %ld
", time(NULL));

doSomthing();
doSomthingLong();

printf("**MyProgram::after time= %ld
", time(NULL));

我试过了:

struct timeval diff, startTV, endTV;

gettimeofday(&startTV, NULL); 

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL); 

timersub(&endTV, &startTV, &diff);

printf("**time taken = %ld %ld
", diff.tv_sec, diff.tv_usec);

如何读取 **time take = 0 26339 的结果?这是否意味着 26,339 纳秒 = 26.3 毫秒?

How do I read a result of **time taken = 0 26339? Does that mean 26,339 nanoseconds = 26.3 msec?

**time take = 4 45025 怎么样,这是否意味着 4 秒 25 毫秒?

What about **time taken = 4 45025, does that mean 4 seconds and 25 msec?

推荐答案

//***C++11 Style:***
#include <chrono>

std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "[µs]" << std::endl;
std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << "[ns]" << std::endl;

这篇关于轻松测量经过的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆