容易测量过的时间我试着用时间()来测量我节目的各个方面。我不明白的是,为什么前后的值是一样的?我知道这不是最好的方式来分析我的程序,我只是想看看需要多长时间。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);我如何读到**time taken = 0 26339?这是否意味着26,339纳秒=26.3毫秒?关于**time taken = 4 45025,这是否意味着4秒25毫秒?
3 回答
四季花海
TA贡献1811条经验 获得超5个赞
#include <ctime>void f() { using namespace std; clock_t begin = clock(); code_to_time(); clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;}
time()
CLOCKS_PER_SEC
HUWWW
TA贡献1874条经验 获得超12个赞
#include <iostream>#include <chrono>template<typename TimeT = std::chrono::milliseconds>struct measure{ template<typename F, typename ...Args> static typename TimeT::rep execution(F&& func, Args&&... args) { auto start = std::chrono::steady_clock::now(); std::forward<decltype(func)>(func)(std::forward<Args>(args)...); auto duration = std::chrono::duration_cast< TimeT> (std::chrono::steady_clock::now() - start); return duration.count(); }};int main() { std::cout << measure<>::execution(functor(dummy)) << std::endl;}
count
template<typename F, typename ...Args>static auto duration(F&& func, Args&&... args){ auto start = std::chrono::steady_clock::now(); std::forward<decltype(func)>(func)(std::forward<Args>(args)...); return std::chrono::duration_cast<TimeT>(std::chrono::steady_clock::now()-start);} // call .count() manually later when needed (eg IO)auto avg = (measure<>::duration(func) + measure<>::duration(func)) / 2.0;
“想要在I/O之前对一系列持续时间进行后处理(例如平均值)”
std::invoke
execution
invoke(forward<decltype(func)>(func), forward<Args>(args)...);
MMTTMM
TA贡献1869条经验 获得超4个赞
//***C++11 Style:***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() <<std::endl;std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() <<std::endl;
- 3 回答
- 0 关注
- 651 浏览
添加回答
举报
0/150
提交
取消