gpt4 book ai didi

c++ - 计算c++中操作之间的时间长度

转载 作者:太空狗 更新时间:2023-10-29 23:34:06 25 4
gpt4 key购买 nike

该程序是数据库和应用程序之间的中间件。对于每次数据库访问,我大多数以毫秒为单位计算时间长度。下面的示例使用 Builder 库中的 TDateTime。我必须尽可能只使用标准 C++ 库。

AnsiString TimeInMilliseconds(TDateTime t) {
Word Hour, Min, Sec, MSec;
DecodeTime(t, Hour, Min, Sec, MSec);
long ms = MSec + Sec * 1000 + Min * 1000 * 60 + Hour * 1000 * 60 * 60;
return IntToStr(ms);
}
  // computing times
TDateTime SelectStart = Now();
sql_manipulation_statement();
TDateTime SelectEnd = Now();

最佳答案

在 Windows 和 POSIX 兼容系统(Linux、OSX 等)上,您可以使用 clock() 以 1/CLOCKS_PER_SEC(计时器滴答)计算时间在 <ctime> 中找到.该调用的返回值将是自程序开始运行以来耗时(以毫秒为单位)。两次调用 clock()然后可以相互减去计算给定代码块的运行时间。

例如:

#include <ctime>
#include <cstdio>

clock_t time_a = clock();

//...run block of code

clock_t time_b = clock();

if (time_a == ((clock_t)-1) || time_b == ((clock_t)-1))
{
perror("Unable to calculate elapsed time");
}
else
{
unsigned int total_time_ticks = (unsigned int)(time_b - time_a);
}

编辑:您将无法直接比较从 POSIX 兼容平台到 Windows 平台的时间,因为在 Windows 上 clock()测量挂钟时间,而在 POSIX 系统上,它测量经过的 CPU 时间。但它是标准 C++ 库中的函数,用于比较同一平台上不同代码块之间的性能,应该符合您的需要。

关于c++ - 计算c++中操作之间的时间长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6125671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com