Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【文章推荐】如何用 Stopwatch 正确的计算耗时 #753

Open
gaufung opened this issue Nov 4, 2024 · 1 comment
Open

【文章推荐】如何用 Stopwatch 正确的计算耗时 #753

gaufung opened this issue Nov 4, 2024 · 1 comment

Comments

@gaufung
Copy link
Collaborator

gaufung commented Nov 4, 2024

https://www.youtube.com/watch?v=Lvdyi5DWNm4&ab_channel=NickChapsas

@gaufung
Copy link
Collaborator Author

gaufung commented Nov 27, 2024

image

C# 中的 Stopwatch 类用来测量程序运行的耗时,通常的代码逻辑是这样的

var sw = Stopwatch.StartNew()
// do your wok
sw.Stop();
Console.WriteLine($"Elapsed time: {sw.Elapsed.Microseconds} ms");

从性能角度来看,这段代码的问题是 Stopwatch 是要给 class 类型,每次都会在堆上分配一个对象,增加垃圾回收的负担。所以 Stopwatch 类提供了一个更加高效的实现

long startTime = Stopwatch.GetTimestamp();
// do you work
var elapsedTime = Stopwatch.GetElapsedTime(startTime);
Console.WriteLine($"Elapsed time: {elapsedTime.Microseconds} ms");

该方法调用的系统函数中的 tick 的方法,然后根据不同的 tick 的差值,计算出中间经历的时间。这个过程中,不会进行任何堆内存分配。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant