﻿ c – 如何以毫秒为单位获取当前时间？ - 代码日志

#### c – 如何以毫秒为单位获取当前时间？

``````#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;
}
``````

Ps：如果您的编译器不支持,那么您可以查看我的Time Measurements (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()` function returns time relative to which time?

std::chrono开始：

Time points

A reference to a specific point in time, like one’s
birthday, today’s dawn, or when the next train passes. In this
library, objects of the time_point class template express this by
using a duration relative to an epoch (which is a fixed point in time
common to all time_point objects using the same clock).

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