为什么用 Numpy 的矩阵乘法比用gsl_blas_sgemmGSL快得多,例如:
import numpy as np
import time
N = 1000
M = np.zeros(shape=(N, N), dtype=np.float)
for i in range(N):
for j in range(N):
M[i, j] = 0.23 + 100*i + j
tic = time.time()
np.matmul(M, M)
toc = time.time()
print(toc - tic)
Run Code Online (Sandbox Code Playgroud)
给出 0.017 - 0.019 秒之间的值,而在 C++ 中:
#include <chrono>
#include <iostream>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
using namespace std::chrono;
int main(void) {
int N = 1000;
gsl_matrix_float* M = gsl_matrix_float_alloc(N, N);
for (int i = …Run Code Online (Sandbox Code Playgroud) 在我的 Ubuntu 20 平台(使用 g++ 9.3.0)上的项目中,我使用以下行
#include <execution>
Run Code Online (Sandbox Code Playgroud)
通过标准库函数支持并行处理。我没有包含来自英特尔并行执行库 TBB 的任何内容。但是当我构建程序时,我收到消息:
#include <execution>
Run Code Online (Sandbox Code Playgroud)
-ltbb通过添加到链接器行,这很容易解决(例如:使消息消失) 。但后来我对 libtbb 产生了依赖,但我并没有指望它。
这种依赖性是预期的吗?是否可以在不安装的情况下使用并行执行tbb(但这tbb会覆盖安装时的默认设置)?
假设我有两个向量并希望获取它们的点积;这很简单,
import numpy as np
a = np.random.rand(3)
b = np.random.rand(3)
result = np.dot(a,b)
Run Code Online (Sandbox Code Playgroud)
如果我有一堆向量并且我希望每个向量都被点缀,那么最简单的代码是
# 5 = number of vectors
a = np.random.rand(5,3)
b = np.random.rand(5,3)
result = [np.dot(aa,bb) for aa, bb in zip(a,b)]
Run Code Online (Sandbox Code Playgroud)
批处理此计算的两种方法是使用乘法和求和以及 einsum,
result = np.sum(a*b, axis=1)
# or
result = np.einsum('ij,ij->i', a, b)
Run Code Online (Sandbox Code Playgroud)
但是,这些都不会分派到 BLAS 后端,因此仅使用单个核心。N当非常大时,比如 100 万,这并不是很好。
tensordot确实分派到 BLAS 后端。使用tensordot进行此计算的一种糟糕方法是
np.diag(np.tensordot(a,b, axes=[1,1])
Run Code Online (Sandbox Code Playgroud)
这很糟糕,因为它分配了一个N*N矩阵,而大多数元素都是浪费的。
另一种(非常快)的方法是隐藏的inner1d函数
from numpy.core.umath_tests import inner1d
result = inner1d(a,b)
Run Code Online (Sandbox Code Playgroud)
但这似乎不可行,因为可能公开导出它的问题已经过时了。这仍然归结为用 C 语言编写循环,而不是使用多个内核。
有没有办法在多个核心上同时获得dot …
我有以下 pandas dataframe df
column1 column2 list_numbers sublist_column
x y [10,-6,1,-4]
a b [1,3,7,-2]
p q [6,2,-3,-3.2]
Run Code Online (Sandbox Code Playgroud)
sublist_column 将包含“list_numbers”列中的数字,其总和为 0(0.5 是一个容差)我编写了以下代码。
def return_list(original_lst,target_sum,tolerance):
memo=dict()
sublist=[]
for i, x in enumerate(original_lst):
if memo_func(original_lst, i + 1, target_sum - x, memo,tolerance) > 0:
sublist.append(x)
target_sum -= x
return sublist
def memo_func(original_lst, i, target_sum, memo,tolerance):
if i >= len(original_lst):
if target_sum <=tolerance and target_sum>=-tolerance:
return 1
else:
return 0
if (i, target_sum) not in memo:
c = memo_func(original_lst, i + 1, target_sum, memo,tolerance) …Run Code Online (Sandbox Code Playgroud) 从如何从两个制表符分隔的文件中获取枢轴线?,有一种使用 unix 命令从两个文件中透视行的快速方法。
如果我们有两对文件:
f1a 和 f1bf2a 和 f2b目标是提供一个 3 列制表符分隔的文件,其中包括:
f1a / f2a文件中同时出现在f1a和中的行在哪里f1b:
我尝试了以下可行的方法,但如果文件非常大,则将需要大量内存来存储f1和f2字典。例如具有数十亿行的文件。
import sys
from tqdm import tqdm
f1a, f1b, f2a, f2b = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
# Read first pair of file into memory.
with open(f1a) as fin_f1a, open(f1a) as fin_f1b:
f1 = {s.strip().replace('\t', ' ') :t.strip().replace('\t', ' ') for s, t in tqdm(zip(fin_f1a, fin_f1b))}
with open(s2) as …Run Code Online (Sandbox Code Playgroud) 我想使用数百万个数据点(以小数表示)运行 100k+ 次模拟。我选择小数而不是浮点数是为了浮点精度和易于对我的逻辑进行单元测试(因为0.1 + 0.1 + 0.1浮点数不等于 0.3...)。
我希望通过使用 PyPy 来加快模拟速度。但在我的测试过程中,我遇到了 PyPy 无法处理decimal.Decimal甚至_pydecimal.Decimal根本无法处理的情况,并且比 CPython 解释器(使用 C 进行decimal.Decimal算术)慢得多。因此,我复制/粘贴了整个代码库,并将所有Decimals 替换为floats,性能得到了巨大的提升:PyPy 比 CPython 快 60-x70 倍 - 但牺牲了准确性。
是否有任何解决方案可以在 PyPy 中使用小数精度并具有性能优势?我“可以”维护两个代码库:float用于批量运行 100k 模拟,Decimal用于稍后检查有趣的结果 - 但这需要维护两个代码库的开销......
以下是我在Raspberry Pi 4 (Ubuntu Server 20.10, 4 x 1.5GHZ ARM Cortex-A72, 8GB RAM)重现时运行的一些简单测试:
test_decimal.py
import time
from decimal import Decimal
start = time.time()
val = Decimal('1.0')
mul = Decimal('1.000001')
for …Run Code Online (Sandbox Code Playgroud) 我有一个包含 10,000 行的数据框,我试图将这些行的所有可能组合相加。根据我的计算,大约有 5000 万种组合。我将举一个小例子来简化我的数据的样子:
df = Ratio Count Score
1 6 11
2 7 12
3 8 13
4 9 14
5 10 15
Run Code Online (Sandbox Code Playgroud)
这是想要的结果:
results = Min Ratio Max Ratio Total Count Total Score
1 2 13 23
1 3 21 36
1 4 30 50
1 5 40 65
2 3 15 25
2 4 24 39
2 5 34 54
3 4 17 27
3 5 27 42
4 5 19 29
Run Code Online (Sandbox Code Playgroud)
这是我想出的代码来完成计算:
for i in …Run Code Online (Sandbox Code Playgroud) 点云到点云的距离可以使用最近邻距离简单地计算。问题是最近邻不一定是云表示的表面上实际最近的点。\xc2\xa0特别是在我们的例子中:参考云的密度较低。在本例中,使用了插值技术(伪代码):
\nfrom scipy import interpolate\nimport numpy as np\n\nref_point_cloud = np.load("ref_point_cloud.npy").item() # Grid\nf = interpolate.interp2d(ref_point_cloud[\'x\'], ref_point_cloud[\'y\'], ref_point_cloud[\'z\'], kind=\'linear\', copy=False, bounds_error=True)\n\n#### Read dense point cloud (point_cloud_dense) code here ####\n\nfor point in point_cloud_dense:\n distance = abs(f(point(x), point(y)) - ref_point_cloud[\'z\'])\nRun Code Online (Sandbox Code Playgroud)\n插值似乎是一种耗时的技术,但它确实有效。是否有更省时的技术来计算点相对于参考点云的距离?
\n最终目标:使用仅包含地面点的参考点云,从密集的 MLS 点云中删除地面点。距离阈值将决定一个点是否属于地面。
\n参考文献:\n https://www.cloudcompare.org/doc/wiki/index.php?title=Cloud-to-Cloud_Distance \n https://pointclouds.org/documentation/tutorials/kdtree_search.html
\n\n我有一个程序,其主要性能瓶颈涉及一个维度为 1 且另一个维度较大(例如 1000)的矩阵相乘:
\nlarge_dimension = 1000\n\na = np.random.random((1,))\nb = np.random.random((1, large_dimension))\n\nc = np.matmul(a, b)\nRun Code Online (Sandbox Code Playgroud)\n换句话说,将矩阵b与标量相乘a[0]。
我正在寻找最有效的方法来计算这个,因为这个操作重复了数百万次。
\n我测试了两种简单方法的性能,它们实际上是等效的:
\n%timeit np.matmul(a, b)\n>> 1.55 \xc2\xb5s \xc2\xb1 45.8 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\n\n%timeit a[0] * b\n>> 1.77 \xc2\xb5s \xc2\xb1 34.6 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n有没有更有效的方法来计算这个?
\n我正在寻找一些帮助或提示来加速我的代码。
我已经实现了一个例程,用于根据一组球谐系数 C_{n,m} 和 S_{n,m} 计算空间中某个点 (r,phi,lambda) 的引力势。等式显示在下面的链接中:
并且包括与纬度 (phi) 相关的关联勒让德多项式 P_{n,m} 的递归计算,从前两个值 P{0,0} 和 P_{1,1} 开始。
起初,我将其作为 MATLAB C-MEX 代码实现,只有我代码的核心部分是用 C 语言编写的。我想做一个纯C程序,但发现代码运行速度慢了3-5倍,这让我想知道为什么。这可能是我定义结构并使用指向中央代码中的指针的方式吗?看起来它是需要额外时间的核心计算部分,但该部分没有改变,尽管在我将指针直接传递给变量之前,现在我在结构内部使用指针。任何帮助表示赞赏!
在下文中,我将尝试解释我的代码并展示一些摘录:
在程序开始时,我定义了三个结构。一个保存球谐系数,C_{n,m} 和 S_{n,m}, (ggm_struct),一个保存计算坐标 (comp_struct),一个保存结果 (func_struct):
// Define constant variables
const double deg2rad = M_PI/180.0; // degrees to radians conversion factor
const double sfac = 1.0000E-280; // scaling factor
const double sqrt2 = 1.414213562373095; // sqrt(2)
const double sqrt3 = 1.732050807568877; // sqrt(3)
// Define structure to hold geopotential model
struct ggm_struct {
char product_type[100], modelname[100], …Run Code Online (Sandbox Code Playgroud) performance ×8
python ×8
numpy ×5
c++ ×2
pandas ×2
c ×1
combinations ×1
csv ×1
dictionary ×1
execution ×1
gsl ×1
math ×1
point-clouds ×1
pointers ×1
pypy ×1
scalar ×1
std ×1
structure ×1
tbb ×1