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

PLS*_*PLS 2 c++ time tdatetime

该程序是数据库和应用程序之间的中间件.对于每个数据库访问,我大多数以毫秒为单位计算时间长度.下面的示例是使用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);
  }
Run Code Online (Sandbox Code Playgroud)
  // computing times
   TDateTime SelectStart = Now();
   sql_manipulation_statement();
   TDateTime SelectEnd = Now();
Run Code Online (Sandbox Code Playgroud)

Jas*_*son 8

在Windows和POSIX兼容的系统(Linux,OSX等)两种,你可以算算时间在1/CLOCKS_PER_SEC(计时器滴答声)一个呼叫使用clock()中发现的<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);
}
Run Code Online (Sandbox Code Playgroud)

编辑:您无法直接将POSIX兼容平台的时序与Windows平台进行比较,因为在Windows上clock()测量挂钟时间,而在POSIX系统上,它会测量经过的CPU时间.但它是标准C++库中的一个函数,并且为了比较同一平台上不同代码块之间的性能,应该满足您的需求.