代码之家  ›  专栏  ›  技术社区  ›  HiroIshida

在Julia中使用struct和loop时会有奇怪的减速

  •  1
  • HiroIshida  · 技术社区  · 7 年前

    我对使用和不使用struct的两个函数进行了速度比较,如下所示,它的性能差别很大:0.07899 vs 0.0011[秒]。奇怪的是idxset的内容 test1() 和 test2()

    你能解释一下如何用struct改进我的代码吗?为什么会这样?

    struct Data
        bool
    end
    function test1()
        N = 10^5
        data = Data(trues(N))
        idxset = findall(data.bool)
    
        s=0.0
        @time for i in idxset
            s += i^2
        end
        return s
    end
    
    function test2()
        N = 10^5
        bool = trues(N)
        idxset = findall(bool)
    
        s=0.0
        @time for i in idxset
            s += i^2
        end
        return s
    end
    test1()
    test2()
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Chris Rackauckas    7 年前
    struct Data
        bool
    end
    

    没有关于布尔的任何类型信息,所以 data.bool 无法推断类型,导致函数中的类型不正确,代码速度慢。 数据.bool 不被发现可能会 idxset i 取消查找并减慢运算速度。检查一下这个 @code_warntype . 通过以下方法解决此问题:

    struct Data
        bool::BitArray{1}
    end
    
    推荐文章