标题说明了 - numpy 的 xtensor 等价物是什么
# set all elements > 3 to 1
sometensor[sometensor > 3] = 1
?
看起来 xt::filter
有效:
xt::filter(sometensor, sometensor > 3) = 1
但看起来 numpy 版本要快得多。我已经用 xsimd 构建了 xtensor,但在这种情况下它似乎没有帮助。有没有更好、更简单的方法来做到这一点?
编辑
我找到了 filtration
,它确实更快(大约 3 倍),但仍然比 numpy 慢(大约 10 倍)...
解决方案(感谢汤姆!)
a = xt::where(a > 0.5, 1.0, a);
是最快的 - 大约比 filtration
快 10 倍,所以它看起来像是 simd-d!
答案 0 :(得分:2)
xt::filter
似乎是一个视图,它(目前)在 xtensor 中效率不高。我会使用xt::where
。不过,它可能会导致暂时的,而在 NumPy 中可能不是这种情况。由于我不知道临时的细节,让我们至少做一些时间:
import numpy as np
from datetime import datetime
a = np.random.random([1000000])
start = datetime.now()
a[a > 0.5] = 1.0
stop = datetime.now()
print((stop - start).microseconds)
在我的系统上大约 5000 微秒。
import numpy as np
from datetime import datetime
a = np.random.random([1000000])
start = datetime.now()
a = np.where(a > 0.5, 1.0, a)
stop = datetime.now()
print((stop - start).microseconds)
在我的系统上大约 2500 微秒。
#include <iostream>
#include <chrono>
#include <xtensor.hpp>
using namespace std;
int main()
{
xt::xtensor<double, 1> a = xt::random::rand<double>({1000000});
auto start = std::chrono::high_resolution_clock::now();
a = xt::where(a > 0.5, 1.0, a);
auto stop = std::chrono::high_resolution_clock::now();
auto duration = duration_cast<std::chrono::microseconds>(stop - start);
cout << duration.count() << endl;
}
在我的系统上,使用 xsimd 的时间在 2500 到 5000 微秒之间(比 NumPy 的分布要多得多),而没有 xsimd 的时间大约是其两倍。
#include <iostream>
#include <chrono>
#include <xtensor.hpp>
using namespace std;
int main()
{
xt::xtensor<double, 1> a = xt::random::rand<double>({1000000});
auto start = std::chrono::high_resolution_clock::now();
xt::filter(a, a > 0.5) = 1.0;
auto stop = std::chrono::high_resolution_clock::now();
auto duration = duration_cast<std::chrono::microseconds>(stop - start);
cout << duration.count() << endl;
}
在我的系统上,使用和不使用 xsimd 大约有 30000 微秒。
我用
cmake_minimum_required(VERSION 3.1)
project(Run)
set(CMAKE_BUILD_TYPE Release)
find_package(xtensor REQUIRED)
find_package(xsimd REQUIRED)
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} xtensor xtensor::optimize xtensor::use_xsimd)
没有 xsimd 我省略了最后一行。
我正在运行 Mac 的 M1。列出的时间在 Rosetta 上(即 x86
)。对于本机构建,时间为: