如何记录C 重复迭代函数的总时间
How To record total timing for C++ repetive Iterative function?
我有此功能原型代码用于迭代计算我如何包括一个计时器来产生用于循环100次功能的总时间?
for(未签名的长i = number; i> = 1; i-)结果 *= i;
我的C 知识几乎是基本的,因此不确定此处是否正确提及"循环"。但是,我被暗示要使用。
pls建议
谢谢
这是某些时序逻辑的正确C 11版:
using namespace std;
using namespace chrono;
auto start_time = system_clock::now();
// your loop goes here:
for (unsigned long i=number; i>=1; i--) result *=i;
auto end_time = system_clock::now();
auto durationInMicroSeconds = duration_cast<microseconds>(end_time - start_time);
cout << "Looping " << number << " times took " << durationInMicroSeconds << "microseconds" << endl;
仅用于运动,这是一个简单的基于RAII的变体:
class Timer {
public:
explicit Timer(const string& name)
: name_(name)
, start_time_(system_clock::now()) {
}
~Timer() {
auto end_time = system_clock::now();
auto durationInMicroSeconds = duration_cast<microseconds>(end_time - start_time);
cout << "Timer: " << name << " took " << durationInMicroSeconds << "microseconds" << endl;
}
private:
string name_;
system_clock::time_point start_time_;
};
当然,这是更多的代码,但是一旦拥有,您可以相当有效地重复使用它:
{
Timer timer("loops");
// your loop goes here:
for (unsigned long i=number; i>=1; i--) result *=i;
}
如果您在执行程序代码中的循环语句中花费的时间尝试使用gettimeofday()
如下,
#include <sys/time.h>
struct timeval tv1, tv2;
gettimeofday(&tv1, NULL);
/* Your loop code to execute here */
gettimeofday(&tv2, NULL);
printf("Time taken in execution = %f secondsn",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
此解决方案更多地是针对C
,可以在您的情况下用于计算所花费的时间。
这是lambda的完美情况。老实说,我不知道C 中的语法,但应该是这样的:
duration timer(function f) {
auto start = system_clock::now();
f();
return system_clock::now() - start;
}
要使用它,您将代码包装在lambda中,然后将其传递给计时器。效果与@martin J.的代码非常相似。
duration code_time = timer([] () {
// put any code that you want to time here
}
duration loop_time = timer([] () {
for (unsigned long i=number; i>=1; i--) {
result *=i;
}
}
相关文章:
- 实现一个在集合上迭代的模板函数
- 如何在C++中将迭代器作为函数参数传递
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- 调用迭代函数的次数
- HPX 是否提供具有粒度控制的基于任务的并行化迭代函数?
- 如何将递归函数(具有两个基本情况)转换为迭代函数
- 将递归函数转换为迭代函数
- 当我计算它并给我 O(n^3) 时,这个迭代函数是如何是 O(n/2) 的
- C 的自定义迭代函数
- 如何记录C 重复迭代函数的总时间
- 使用迭代函数调用初始化std::vector
- 将递归可变参数模板函数转换为迭代函数
- 将迭代函数转换为递归函数
- 将迭代函数转换为递归函数
- c++使用迭代函数进行编译
- 模板类中向量向量的迭代函数构建
- 将迭代函数转换为递归函数
- 这个递归函数是如何自动转换成迭代函数的
- 在编译时迭代函数参数类型