Oli*_*rLi 68
如果您使用的是c ++ 11或更高版本,则可以使用std::chrono::high_resolution_clock.
一个简单的用例:
auto start = std::chrono::high_resolution_clock::now();
...
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
该解决方案具有便携的优点.
Gab*_*les 17
新的 C++11std::chrono库是我见过或试图弄清楚如何使用的最复杂的一堆乱七八糟的C++ 之一,但至少它是跨平台的!
所以,如果你想简化它并使它更像 C 语言,包括删除它所做的所有类型安全的类的东西,这里有 3 个简单且非常易于使用的函数来获取时间戳毫秒、微秒和纳秒……我只花了大约 12 小时来写*:
注意:在下面的代码中,您可能会考虑使用std::chrono::steady_clock代替std::chrono::high_resolution_clock。他们在这里的定义(https://en.cppreference.com/w/cpp/chrono)如下:
- stable_clock (C++11) - 永远不会被调整的单调时钟
- high_resolution_clock (C++11) - 可用最短滴答周期的时钟
#include <chrono>
// NB: ALL OF THESE 3 FUNCTIONS BELOW USE SIGNED VALUES INTERNALLY AND WILL EVENTUALLY OVERFLOW (AFTER 200+ YEARS OR
// SO), AFTER WHICH POINT THEY WILL HAVE *SIGNED OVERFLOW*, WHICH IS UNDEFINED BEHAVIOR (IE: A BUG) FOR C/C++.
// But...that's ok...this "bug" is designed into the C++11 specification, so whatever. Your machine won't run for 200
// years anyway...
// Get time stamp in milliseconds.
uint64_t millis()
{
    uint64_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::
                  now().time_since_epoch()).count();
    return ms; 
}
// Get time stamp in microseconds.
uint64_t micros()
{
    uint64_t us = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::
                  now().time_since_epoch()).count();
    return us; 
}
// Get time stamp in nanoseconds.
uint64_t nanos()
{
    uint64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::
                  now().time_since_epoch()).count();
    return ns; 
}
* (抱歉,我更像是一名嵌入式开发人员,而不是标准的计算机程序员,所以所有这些高级抽象静态成员内类内命名空间内命名空间内命名空间内的东西让我感到困惑。唐别担心,我会好起来的。)
std::chrono?A:因为 C++ 程序员喜欢对事物发疯,所以他们让它为你处理单元。以下是一些 C++ 怪异之处和std::chrono. 参考此页面:https : //en.cppreference.com/w/cpp/chrono/duration。
因此,您可以声明一个 1 秒的变量并将其更改为微秒,而无需像这样进行强制转换:
// Create a time object of type `std::chrono::seconds` & initialize it to 1 sec
std::chrono::seconds time_sec(1); 
// integer scale conversion with no precision loss: no cast
std::cout << std::chrono::microseconds(time_sec).count() << " microseconds\n";
你甚至可以像这样指定时间,在我看来,这太奇怪了,而且太过分了。C++14 从字面上重载了字符ms、us、ns等作为函数调用运算符来初始化std::chrono各种类型的对象,如下所示:
auto time_sec = 1s; // <== notice the 's' inside the code there to specify 's'econds!
// OR:
std::chrono::seconds time_sec = 1s;
// integer scale conversion with no precision loss: no cast
std::cout << std::chrono::microseconds(time_sec).count() << " microseconds\n";
以下是更多示例:
std::chrono::milliseconds time_ms = 1ms;
// OR:
auto time_ms = 1ms;
std::chrono::microseconds time_us = 1us;
// OR:
auto time_us = 1us;
std::chrono::nanoseconds time_ns = 1ns;
// OR:
auto time_ns = 1ns;
就我个人而言,我更愿意简化语言并执行此操作,就像我已经做的那样,并且在此之前几十年来在 C 和 C++ 中都已完成:
// Notice the `_sec` at the end of the variable name to remind me this 
// variable has units of *seconds*!
uint64_t time_sec = 1; 
system_clocksteady_clockhigh_resolution_clockutc_clocktai_clockgps_clockfile_clock的operator"" mysuffix()操作者过载/用户定义字面/后缀功能(如C ++ 11的)是如何奇怪auto time_ms = 1ms;事情的作品的上方。写作1ms实际上是一个函数调用功能operator"" ms(),用1在传递作为输入参数,就好像你写一个函数调用是这样的:operator"" ms(1)。要了解有关此概念的更多信息,请参阅此处的参考页面:cppreference.com:用户定义的文字(C++11 起)。
这是定义用户定义的文字/后缀函数的基本演示,并使用它:
// 1. Define a function
// used as conversion from degrees (input param) to radians (returned output)
constexpr long double operator"" _deg(long double deg)
{
    long double radians = deg * 3.14159265358979323846264L / 180;
    return radians;
}
// 2. Use it
double x_rad = 90.0_deg;
为什么不使用更像的东西double x_rad = degToRad(90.0);(就像几十年来在 C 和 C++ 中所做的那样)?我不知道。我猜这与 C++ 程序员的想法有关。也许他们正试图让现代 C++ 更加 Pythonic。
这种魔法也是潜在非常有用的 C++fmt库的工作原理,这里是:https : //github.com/fmtlib/fmt。它由Victor Zverovich编写,他也是 C++20's std::format. 您可以在detail::udl_formatter<char> operator"" _format(const char* s, size_t n) 此处查看该函数的定义。它的用法是这样的:
"Hello {}"_format("World");
输出:
你好,世界
这会将"World"字符串插入到所在的第一个字符串中{}。这是另一个例子:
"I have {} eggs and {} chickens."_format(num_eggs, num_chickens);
示例输出:
我有 29 个鸡蛋和 42 只鸡。
这与Python 中的str.format字符串格式非常相似。在此处阅读 fmt lib 文档。
如果您正在查看从Unix shell执行程序所消耗的时间,请使用Linux 时间,如下所示,
time ./a.out 
real    0m0.001s
user    0m0.000s
sys     0m0.000s
其次,如果你想在程序代码(C)中执行多少语句,请尝试使用gettimeofday(),如下所示,
#include <sys/time.h>
struct timeval  tv1, tv2;
gettimeofday(&tv1, NULL);
/* Program code to execute here */
gettimeofday(&tv2, NULL);
printf("Time taken in execution = %f seconds\n",
     (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
     (double) (tv2.tv_sec - tv1.tv_sec));
| 归档时间: | 
 | 
| 查看次数: | 43765 次 | 
| 最近记录: |