我正在尝试使用 mypy 来检查我的程序。该程序使用 argparse 来解析命令行参数。我想为命令行参数添加类型提示。
import argparse
import typing
# define example types and a function that uses them
Seconds = typing.NewType("Seconds", float)
Minutes = typing.NewType("Minutes", float)
def sec_to_min(s: Seconds) -> Minutes:
return Minutes(s / 60)
# specify arguments and parse them
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--time", default=1., type=float,
help="time in seconds")
args = parser.parse_args()
try:
# mypy reveals type Any
reveal_type(args.time)
except NameError:
pass
# (1) passes type check
seconds: Seconds = args.time
# (2) passes type check
sec_to_min(args.time) …
Run Code Online (Sandbox Code Playgroud) 我编写了一个计时函数,记录了函数的运行时间,并计算了多次运行的均值和标准差。我惊讶地发现即使是看似简单的任务(例如加两个双打)也有很高的标准偏差。我分析了python中的数据(请参见图)。C ++输出是19.6171 ns +/- 21.9653ns (82799807 runs)
使用以下命令编译的:
gcc version 8.3.0 (Debian 8.3.0-19)
/usr/bin/c++ -O3 -DNDEBUG -std=gnu++17
Run Code Online (Sandbox Code Playgroud)
整个测试是在我的个人计算机上完成的,该计算机不是空闲的而是运行DE,浏览器,IDE和其他进程。测试期间有可用的RAM。我的带有HT的双核CPU空闲率低于10%。
在这种情况下,是否会出现从20 ns的平均值到50 µs的峰值?
运行时间图
这是的内容std::vector<double> run_times
。我没有看到任何图案。
定时
gcc version 8.3.0 (Debian 8.3.0-19)
/usr/bin/c++ -O3 -DNDEBUG -std=gnu++17
Run Code Online (Sandbox Code Playgroud)
计时文件
#include <cstdint>
#include <ostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <chrono>
#include <numeric>
#include <fstream>
struct TimingResults{
// all time results are in nanoseconds
double mean;
double standard_deviation;
uint64_t number_of_runs;
};
std::ostream& operator<<(std::ostream& os, const TimingResults& results);
template …
Run Code Online (Sandbox Code Playgroud)