python for循环每次迭代都会变慢(python for-loop slower each iteration)
我正在尝试优化一些python代码(以加快一些矩阵操作),我的代码类似于这个(我的真实数据集也类似于'gps'),
import numpy as np gps = [np.random.rand(50,50) for i in xrange(1000)] ips = np.zeros( (len(gps),len(gps)), dtype='float32') for i in xrange(len(gps)): for j in xrange(0,i+1): ips[i,j]= f.innerProd(gps[i],gps[j]) ips[j,i]= ips[i,j] print "Inner product matrix: %3.0f %% done (%d of %d)"% \ (((i+1)**2.)/(len(gps)**2.)*100, i, len(gps)) def innerProd(mat1,mat2): return float(np.sum(np.dot(np.dot(mat1,mat2),mat1)))
我想要理解的是,为什么程序在第一次迭代期间开始快速运行,然后在进一步迭代时减慢? 我知道这个问题可能有点天真但我真的想在我尝试其他任何事情之前更清楚地了解发生了什么。 我已经在Fortran中实现了我的函数(在Fortran域中留下任何for循环)并使用f2py创建一个动态lib来从python调用函数,这将是python中的新代码。
import numpy as np import myfortranInnProd as fip gps = [np.random.rand(50,50) for i in xrange(1000)] ips = np.zeros( (len(gps),len(gps)), dtype='float32') ips = fip.innerProd(gps)
不幸的是,我发现(令人惊讶的是)我的fortran-python版本运行速度比第一个版本慢1.5~2倍(重要的是要提到我在Fortran实现上使用了MATMUL())。 我一直在谷歌搜索一段时间,我相信这种“减速”与内存带宽,内存分配或缓存有关,考虑到大型数据集,但我不太确定背后真正发生的事情以及如何我可以改善表现吗? 我已经在小型英特尔原子,2GB内存和4核英特尔至强处理器上运行代码,8GB(当然还有相应的缩放数据集)并且“减速”行为是相同的。
我只需要理解为什么这种“减速”会发生? 如果我在C中实现该功能,它会有用吗? 或尝试实现它在GPU上运行? 还有其他想法如何改进吗? 提前致谢
I am trying to optimize some python code (to speed up some matrix operations), my code is something similar to this one (my real dataset is also similar to 'gps'),
import numpy as np gps = [np.random.rand(50,50) for i in xrange(1000)] ips = np.zeros( (len(gps),len(gps)), dtype='float32') for i in xrange(len(gps)): for j in xrange(0,i+1): ips[i,j]= f.innerProd(gps[i],gps[j]) ips[j,i]= ips[i,j] print "Inner product matrix: %3.0f %% done (%d of %d)"% \ (((i+1)**2.)/(len(gps)**2.)*100, i, len(gps)) def innerProd(mat1,mat2): return float(np.sum(np.dot(np.dot(mat1,mat2),mat1)))
What I would like to understand is , why is it that the program begins running fast during the first iterations and then slows down as it iterates further? I know the question might be a bit naive but I really want to have a clearer idea of what is happening before I attempt anything else. I already implemented my function in Fortran (leaving within the Fortran realm any for loops) and used f2py to create a dynamic lib to call the function from python, this would be the new code in python..
import numpy as np import myfortranInnProd as fip gps = [np.random.rand(50,50) for i in xrange(1000)] ips = np.zeros( (len(gps),len(gps)), dtype='float32') ips = fip.innerProd(gps)
unfortunately I only found out (surprisingly) that my fortran-python version runs 1.5 ~ 2 times slower than the first version (it is important to mention that I used MATMUL() on the Fortran implementation). I have been googling around for a while and I believe that this "slow down" has something to do with the memory bandwidth, memory allocation or caching, given the large datasets, but I am not very sure about what is really happening behind and how could I improve the performance. I have run the code on both a small intel atom , 2GB ram and a 4 core intel xeon, with 8GB (of course with a correspondingly scaled dataset) and the "slow down" behavior is the same.
I just need to understand why is it that this 'slow down' happens? would it do any good if i implement the function in C ? or try to implement it to run on a GPU ? Any other ideas how to improve it? Thanks in advance
原文:https://stackoverflow.com/questions/5845826
最满意答案
我这样做了:
AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); // Prepare the Interstitial Ad interstitial = new InterstitialAd(this); interstitial.setAdUnitId("ca-app-pub-3940256099942544/1033173712"); interstitial.loadAd(adRequest); interstitial.setAdListener(new AdListener() { public void onAdLoaded() { displayInterstitial(); } public void onAdClosed() { requestNewInterstitial(); } }); } public void displayInterstitial() { // If Ads are loaded, show Interstitial else show nothing. if (interstitial.isLoaded()) { interstitial.show(); } } public void requestNewInterstitial() { mHandler.postDelayed(new Runnable() { @Override public void run() { AdRequest adRequest = new AdRequest.Builder() .build(); interstitial.loadAd(adRequest); if (mHandler != null) { mHandler.postDelayed(this, 100000); //time (ms) } } }, 100000); //time (ms) }
I did it this way :
AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); // Prepare the Interstitial Ad interstitial = new InterstitialAd(this); interstitial.setAdUnitId("ca-app-pub-3940256099942544/1033173712"); interstitial.loadAd(adRequest); interstitial.setAdListener(new AdListener() { public void onAdLoaded() { displayInterstitial(); } public void onAdClosed() { requestNewInterstitial(); } }); } public void displayInterstitial() { // If Ads are loaded, show Interstitial else show nothing. if (interstitial.isLoaded()) { interstitial.show(); } } public void requestNewInterstitial() { mHandler.postDelayed(new Runnable() { @Override public void run() { AdRequest adRequest = new AdRequest.Builder() .build(); interstitial.loadAd(adRequest); if (mHandler != null) { mHandler.postDelayed(this, 100000); //time (ms) } } }, 100000); //time (ms) }
相关问答
更多-
插页式广告不会显示(Interstitial Ad Will Not Display)[2023-07-16]
您在清单中缺少以下活动:一种解决方案是实现UINavigationControllerDelegate ,特别是navigationController:willShowViewController:animated: . 当您检测到要显示插页式广告时,请从willShowViewController调用rootVC的func presentViewController()方法并传递插页式视图控制器。 One solution would be to implement UINavigationControllerDelegate ...我这样做了: AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); // Prepare the Interstitial Ad interstitial = new InterstitialAd(this); interstitial.setAdUni ...如何使用swift,spritekit和xcode调用admob插页式广告?(How to call admob interstitial ad using swift, spritekit and xcode?)[2022-12-26]
好吧,我开始了一个新项目(Swift项目),它是Game Project 在GameViewController中: class GameViewController: UIViewController { var interstitial = GADInterstitial() override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") ...对不起Jocheved的晚期重播。 如果在每部手机中都没有出现此问题,则可能是该用户的移动设置存在问题。 只需检查是否选择了他/她的“设置>开发人员选项>不保持活动”。 如果选中它,则应用程序将在用户离开当前活动后立即销毁所有活动。 因此,当显示插页式广告时,当前活动通常会在onPause中。 但它将被销毁,当用户关闭插页式广告并再次返回时,oncreate将会运行,广告将会显示。 为避免这种情况,您可以通知用户检查选项是否被选中..否则您可能需要找到其他解决方案并通过编程解决。 谢谢.. Sorry Jo ...当然这是打电话。 这就是你告诉它与UIApplication.shared.open做的事情。 在interstitialDidDismissScreen解除广告后拨打电话。 同时检查是否有要展示的广告, interstitialAd.isReady 。 如果没有广告要直接拨打电话。 您还在viewDidLoad执行了两次相同的操作: // Sets up an ad self.interstitialAd = GADInterstitial(adUnitID: "ca-app-pub-/696678053 ...预加载插页式广告(Preloading Interstitial ads)[2021-10-26]
无法相信没有人知道这件事,或者不愿意提供帮助。 我会在这里发布答案,希望这实际上可以帮助有需要的人。 我在onCreate()中调用以下方法: requestNewInterstitial(); 方法如下: private void requestNewInterstitial() { AdRequest adRequest = new AdRequest.Builder() .build(); mInterstitialAd.loadAd(adRequest); ...不止一次显示插页式广告(Show interstitial ad more than once)[2022-07-06]
用此重新OnAdClosed() @Override public void onAdClosed () { AdRequest adRequest = new AdRequest.Builder() .build(); interstitial.loadAd(adRequest); } Relpce OnAdClosed() with this ...需要帮助在Spritekit iOS游戏中集成插页式广告(Need Help Integrating Interstitial ads in Spritekit iOS Game)[2022-02-17]
在你的GameViewController ,在viewWillLayoutSubviews设置一个通知观察器,如下所示: override func viewWillLayoutSubviews() { NotificationCenter.default.addObserver(self, selector: #selector(self.showAd), name: NSNotification.Name(rawValue: "showAd"), object: nil) } 然后在你的 ...使用int跟踪操作,创建一个增加它的方法,并检查是否应该显示广告。 如果是,请展示广告并重置广告。 private static int x = 0; public static void incrementActions() { x++; if(x >= 5) { x = 0; displayInterstital(); } } 例如,将它放在MainActivity中,并像这样调用它: MainActivity.incrementActions ...相关文章
更多- 探索 Python,第 1 部分: Python 的内置数值类型
- python2和python3的区别
- Python的文件类型
- python的下载与安装
- Python学习笔记
- Python资源索引 【转载】
- Python基础 缩进和选择
- Python 写的Hadoop小程序
- solr python client
- Python基础 运算
最新问答
更多- 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
- 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
- OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
- 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
- codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
- 在计算机拍照在哪里进入
- 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
- No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
- 单页应用程序:页面重新加载(Single Page Application: page reload)
- 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
- System.StackOverflow错误(System.StackOverflow error)
- KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
- 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
- android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
- TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
- 企业安全培训的各项内容
- 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
- C#类名中允许哪些字符?(What characters are allowed in C# class name?)
- NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
- 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
- 将多个行和可变行移动到列(moving multiple and variable rows to columns)
- 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
- 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
- Angular $资源不会改变方法(Angular $resource doesn't change method)
- 在Angular 5中不是一个函数(is not a function in Angular 5)
- 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
- 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
- 常见的python rpc和cli接口(Common python rpc and cli interface)
- Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
- 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)