---
title: "c++11 chrono"
author: "tcspecial"
date: "2019-02-10T12:44:35Z"
tags: []
categories: ["编程语言"]
slug: "c-11-chrono"
draft: false
lastmod: "2019-02-12T14:44:07Z"
id: 2437404
url: "https://tcspecial.iteye.com/blog/2437404"
---

chrono是c++11中的时间库，提供了大量操作时间的API。

程序睡眠：

```
std::this_thread::sleep_for( std::chrono::seconds(10) );
```

 

上述代码过于繁琐，可简化：

```
using namespace std::chrono_literals;
std::this_thread::sleep_for(10s);
```

  

实现源码：

```
constexpr std::chrono::seconds operator ""s(unsigned long long s)
{
    return std::chrono::seconds(s);
}
```

 

constexpr是C++11中新增的关键字，其语义是“常量表达式”，也就是在编译期可求值的表达式。实现重载了""操作符，因此10s返回的是seconds类型，遗憾的是该特性只有c++14才支持。