簡體   English   中英

如何以毫秒為單位獲取當前時間?

[英]How to get current time in milliseconds?

我是 C++ 的新手,我對它的庫知之甚少。 我需要對不同的排序算法進行時間分析,為此我需要以毫秒為單位獲取當前時間。 有沒有辦法做到這一點?

只需使用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;
}

您無需打印星星,而是將排序算法放在那里並進行時間測量。


不要忘記為您的編譯器啟用優化標志,如果您打算進行一些基准測試,例如對於 ,您需要-O3 這很嚴重,檢查我沒有這樣做時發生了什么: 為什么 emplace_back 比 push_back 快?


Ps:如果您的編譯器不支持 ,那么您可以查看我的Time Measurements (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;
}

現在的輸出是:

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.

就這么簡單。 快樂的基准測試! =)


編輯:

high_resolution_clock::now()函數返回相對於哪個時間的時間?

std::chrono

時間點

對特定時間點的引用,例如生日、今天的黎明或下一趟火車經過的時間。 在這個庫中,time_point 類模板的對象通過使用相對於紀元的持續時間(這是使用相同時鍾的所有 time_point 對象共有的固定時間點)來表達這一點。

在哪里可以檢查這個epoch 和 time_point 示例,它輸出:

time_point tp is: Thu Jan 01 01:00:01 1970

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM