计算方法的执行时间 [英] Calculate the execution time of a method

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

问题描述

可能的重复:
如何衡量函数运行的时间?

我有一个 I/O 计时方法,可以将数据从一个位置复制到另一个位置.计算执行时间的最佳和最真实的方法是什么?线程?定时器?秒表?还有其他解决方案吗?我想要最准确的,尽可能简短的.

I have an I/O time-taking method which copies data from a location to another. What's the best and most real way of calculating the execution time? Thread? Timer? Stopwatch? Any other solution? I want the most exact one, and briefest as much as possible.

推荐答案

Stopwatch 就是为此目的而设计的,它是在 .NET 中测量时间执行的最佳方法之一.

Stopwatch is designed for this purpose and is one of the best ways to measure time execution in .NET.

var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

不要 使用 DateTime 测量 .NET 中的时间执行.

Do not use DateTime to measure time execution in .NET.

更新:

正如@series0ne 在评论部分指出的那样:如果您想真正精确地测量某些代码的执行情况,则必须使用操作系统内置的性能计数器.以下答案 包含一个很好的概述.

As pointed out by @series0ne in the comments section: If you want a real precise measurement of the execution of some code, you will have to use the performance counters that's built into the operating system. The following answer contains a nice overview.

这篇关于计算方法的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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