计算 c++ 中操作之间的时间长度
该程序是数据库和应用程序之间的中间件。对于每次数据库访问,我大多数以毫秒为单位计算时间长度。下面的示例使用 Builder 库中的 TDateTime。我必须尽可能只使用标准 C++ 库。
AnsiString TimeInMilliseconds(TDateTime t) { 字时、分、秒、毫秒; 解码时间(t,小时,分钟,秒,毫秒); 长毫秒 = 毫秒 + 秒 * 1000 + 分钟 * 1000 * 60 + 小时 * 1000 * 60 * 60; 返回 IntToStr(ms); }
// computing times
TDateTime SelectStart = Now();
sql_manipulation_statement();
TDateTime SelectEnd = Now();
The program is a middleware between a database and application. For each database access I most calculate the time length in milliseconds. The example bellow is using TDateTime from Builder library. I must, as far as possible, only use standard c++ libraries.
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Windows 和 POSIX 兼容系统(Linux、OSX 等)上,您可以使用
< 中的
。该调用的返回值将是自程序开始运行以来经过的时间(以毫秒为单位)。然后可以将两次对clock()
来计算调用的时间,单位为 1/CLOCKS_PER_SEC(计时器滴答声) ;ctime>clock()
的调用相减,以计算给定代码块的运行时间。例如:
编辑:您将无法直接比较 POSIX 兼容平台与 Windows 平台的计时,因为在 Windows 上
clock()
测量挂钟时间,其中-与 POSIX 系统一样,它测量所用的 CPU 时间。但它是标准 C++ 库中的一个函数,用于比较同一平台上不同代码块之间的性能,应该适合您的需求。On both Windows and POSIX-compliant systems (Linux, OSX, etc.), you can calculate the time in 1/CLOCKS_PER_SEC (timer ticks) for a call using
clock()
found in<ctime>
. The return value from that call will be the elapsed time since the program started running in milliseconds. Two calls toclock()
can then be subtracted from each other to calculate the running time of a given block of code.So for example:
Edit: You are not going to be able to directly compare the timings from a POSIX-compliant platform to a Windows platform because on Windows
clock()
measures the the wall-clock time, where-as on a POSIX system, it measures elapsed CPU time. But it is a function in a standard C++ library, and for comparing performance between different blocks of code on the same platform, should fit your needs.在 Windows 上,您可以使用 GetTickCount (MSDN) 这将给出自系统启动以来经过的毫秒数。在通话之前和之后使用它,您可以获得通话所花费的毫秒数。
编辑:
正如杰森提到的,Clock();会更好,因为它不仅仅与 Windows 相关。
On windows you can use GetTickCount (MSDN) Which will give the number of milliseconds that have elapsed since the system was started. Using this before and after the call you get the amount of milliseconds the call took.
Edit:
As Jason mentioned, Clock(); would be better because it is not related to Windows only.