gpt4 book ai didi

c# - Bitmap.SetPixel 在 f# 中的行为比在 c# 中慢

转载 作者:可可西里 更新时间:2023-11-01 08:40:42 26 4
gpt4 key购买 nike

f# 代码实际上比 c# 代码慢 500 倍。我究竟做错了什么?我试图使两种语言的代码基本相同。 SetPixel 在 f# 中慢得多是没有意义的。

F#:

module Imaging
open System.Drawing;
#light
type Image (width : int, height : int) = class
member z.Pixels = Array2D.create width height Color.White

member z.Width with get() = z.Pixels.GetLength 0

member z.Height with get() = z.Pixels.GetLength 1

member z.Save (filename:string) =
let bitmap = new Bitmap(z.Width, z.Height)
let xmax = bitmap.Width-1
let ymax = bitmap.Height-1
let mutable bob = 0;
for x in 0..xmax do
for y in 0..ymax do
bitmap.SetPixel(x,y,z.Pixels.[x,y])
bitmap.Save(filename)

new() = Image(1280, 720)
end
let bob = new Image(500,500)
bob.Save @"C:\Users\White\Desktop\TestImage2.bmp"

C#:

using System.Drawing;

namespace TestProject
{
public class Image
{

public Color[,] Pixels;
public int Width
{
get
{
return Pixels.GetLength(0);
}
}
public int Height
{
get
{
return Pixels.GetLength(1);
}
}

public Image(int width, int height)
{
Pixels = new Color[width, height];
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < Height; y++)
{
Pixels[x, y] = Color.White;
}
}
}

public void Save(string filename)
{
Bitmap bitmap = new Bitmap(Width, Height);
for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
bitmap.SetPixel(x, y, Pixels[x, y]);
}
}
bitmap.Save(filename);
}
}
class Program
{
static void Main(string[] args)
{
Image i = new Image(500, 500);
i.Save(@"C:\Users\White\Desktop\TestImage2.bmp");
}
}
}

最佳答案

您在 F# 中对 Pixels 属性的定义是错误的:每次访问它的值时(例如,在 Save 的内部循环中),都会重新评估该定义。您应该改用这种形式:

member val Pixels = Array2D.create width height Color.White

当调用构造函数时,这将只对右侧求值一次,然后缓存该值。

关于c# - Bitmap.SetPixel 在 f# 中的行为比在 c# 中慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18341505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com