如何以毫秒为单位获取当前时间?

Yas*_*afa 9 c++ algorithm performance time stl

我是C++的新手,我对它的库知之甚少.我需要对不同的排序算法进行时间分析,我需要以毫秒为单位获取当前时间.有没有办法做到这一点?

gsa*_*ras 20

只需使用std :: chrono.下面的一般例子是"印刷1000颗星"的任务:

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

int main ()
{
  using namespace std::chrono;

  high_resolution_clock::time_point t1 = high_resolution_clock::now();

  std::cout << "printing out 1000 stars...\n";
  for (int i=0; i<1000; ++i) std::cout << "*";
  std::cout << std::endl;

  high_resolution_clock::time_point t2 = high_resolution_clock::now();

  duration<double, std::milli> time_span = t2 - t1;

  std::cout << "It took me " << time_span.count() << " milliseconds.";
  std::cout << std::endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

您不必打印星星,而是将排序算法放在那里,并按时间测量它.


如果您打算进行基准测试,请不要忘记为编译器启用优化标志,例如对于,您需要-O3.这很严重,检查我没有这样做时发生了什么:为什么emplace_back比push_back更快?


Ps:如果您的编译器不支持,那么您可以在我的时间测量(C++)中查看其他方法.


通过使用我的Quicksort(C++),一个特定的(玩具)示例将是:

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

void quickSort(int a[], int first, int last);
int pivot(int a[], int first, int last);
void swap(int& a, int& b);
void swapNoTemp(int& a, int& b);

using namespace std;
using namespace std::chrono;

int main()
{
    int test[] = { 7, -13, 1, 3, 10, 5, 2, 4 };
    int N = sizeof(test)/sizeof(int);

    cout << "Size of test array :"  << N << endl;

    high_resolution_clock::time_point t1 = high_resolution_clock::now();

    // I want to measure quicksort
    quickSort(test, 0, N-1);

    high_resolution_clock::time_point t2 = high_resolution_clock::now();

    duration<double> time_span = t2 - t1;

    std::cout << "It took me " << time_span.count() << " seconds.";
    std::cout << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在的输出是:

Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall -std=c++11 -O3 main.cpp 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
Size of test array :8
It took me 3.58e-07 seconds.
Run Code Online (Sandbox Code Playgroud)

就这么简单.快乐的基准!=)


编辑:

high_resolution_clock::now() 函数返回时间相对于哪个时间?

来自std :: chrono:

时间点

提及特定时间点,例如一个人的生日,今天的黎明,或下一班火车经过的时间.在此库中,time_point类模板的对象通过使用相对于纪元的持续时间(使用相同时钟对所有time_point对象共同的固定时间点)来表达这一点.

可以检查这个epoch和time_point示例,其中输出:

time_point tp is: Thu Jan 01 01:00:01 1970
Run Code Online (Sandbox Code Playgroud)

  • 你可以通过分配一个没有显式强制转换的双精度毫秒来简化你的第一个代码块:`duration <double,std :: milli> time_span = t2 - t1;`.然后你可以打印出来,无需手动转换为毫秒:`<< time_span.count()<<"毫秒."`.您也可以在第二个示例中删除显式的`duration_cast`.编写更可靠的`chrono`代码的其他技巧如下:https://www.youtube.com/watch?v = P32hvk8b13M (2认同)