如何测量一段代码执行的时间? [英] How to measure the time that a piece of code takes to execute?

查看:206
本文介绍了如何测量一段代码执行的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想测量某段代码需要的时间。为此我通常会做这样的事情

Suppose I want to measure the time that a certain piece of code takes. For that I would normally do something like this

clock_t startTime = clock();
//do stuff
//do stuff
//do stuff
//do stuff
float secsElapsed = (float)(clock() - startTime)/CLOCKS_PER_SEC;

如果程序是多线程的并且上下文切换发生在我想测量的部分我如何衡量我的代码执行的时间,排除在其他线程上花费的时间?即使有工具来做,我也非常想知道他们是如何做的。

What if the program is multithreaded and context switches occur within the part which I want to measure? How would I measure the time that my code takes to execute excluding time spent on other threads? Even if there are tools that do it, I would very much like to know how they're doing it.

推荐答案

有多种方法可以衡量代码需要执行多长时间。

There are different ways to measure how long code takes to execute.

如果您对某些功能的相对性能感兴趣,请 profiler 是唯一的方法。注意,这将减弱由于它引起的计算开销而导致的阻塞I / O的影响。

If you are interested in the relative performance of certain functions, a profiler is the only way to go. Note that this will de-emphasise the impact of blocking I/O due to the computation overheads it induces.

如果你想要基于时钟的时间 ,有一些选项。

If you want the clock-based time of certain functions, there are loads of options.

我个人认为 gettimeofday 已经足够了。

Personally I would say gettimeofday is sufficient.

如果您想要精确,请使用 RDTSC

如果您想要获得真正的 精确度,您将需要此类

If you want to get really precise, you'll want something like this

t1 = rdtsc();
t2 = rdtsc();
my_code();
t3 = rdtsc();
my_code_time = (t3-t2) - (t2-t1)

重复此块以考虑线程调度差异,并注意缓存效果。

You will need to repeat this block to account for thread scheduling discrepencies, and also pay attention to cacheing effects.

这篇关于如何测量一段代码执行的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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