[英]Comparison of np.arange with C++ iota, iota is slower
I wrote a small chunk of code to generate a sequence of integers, and compared it with np.arange()
, and I found np.arange()
is faster. 我写了一小段代码来生成一个整数序列,并将它与
np.arange()
,我发现np.arange()
更快。 Anyone can give me some hint if there is any faster C++ implementation of this ? 如果有更快的C ++实现,任何人都可以给我一些提示吗?
Here is the code: 这是代码:
#include <iostream>
#include <chrono>
#include <ctime>
#include <array>
#include <vector>
#include <numeric>
template <typename T>
std::vector<T> range(T start, T end) {
size_t N = (int)floor(end - start) + 1;
std::vector<T> vec(N);
std::iota(vec.begin(), vec.end(), start);
return vec;
}
int main() {
auto start = std::chrono::system_clock::now();
std::vector<int> x_range = range(0, 1024);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
}
Python code is simple: Python代码很简单:
%timeit x = np.arange(0, 1024)
Python time: 1.51e-6 s
C++ time: 1.6e-5 s
Python时间:
1.51e-6 s
C ++时间: 1.6e-5 s
Python is 10 times faster than C++ implementation here. Python比这里的C ++实现快10倍。
Platform: Win10, Visual Studio Community 2017, in both O2 and Ox optimization mode. 平台:Win10,Visual Studio Community 2017,O2和Ox优化模式。 Both get more or less the same order of time-
1.x e-5 s
. 两者都得到或多或少相同的时间顺序 -
1.x e-5 s
。
Thanks everybody, although it is a simple piece of question, but I still learns a lot. 谢谢大家,虽然这是一个简单的问题,但我仍然学到很多东西。
Here is new code which is different from code in the question, maybe the compassion will help some newbies understand better: 这里的新代码与问题中的代码不同,也许慈悲会帮助一些新手更好地理解:
#include <iostream>
#include <chrono>
#include <ctime>
#include <array>
#include <vector>
#include <numeric>
#include <iostream>
template <typename T>
std::vector<T> range(T start, T end) {
size_t N = (int)floor(end - start);
std::vector<T> vec;
vec.reserve(N);
std::iota(vec.begin(), vec.end(), start);
return vec;
}
int main() {
auto start = std::chrono::system_clock::now();
for (int i = 0; i < 100000000; ++i) {
std::vector<int> x_range = range(0, 1000);
}
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
system("pause");
}
Now C++ implementation time: 7.14136e-8 s. 现在C ++实现时间:7.14136e-8 s。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.