【发布时间】:2020-01-27 21:20:02
【问题描述】:
有第二个代码:
class Methods
{
public MemoryStream UniqPicture(string imagePath)
{
var photoBytes = File.ReadAllBytes(imagePath); // change imagePath with a valid image path
var quality = 70;
var format = ImageFormat.Jpeg; // we gonna convert a jpeg image to a png one
var size = new Size(200, 200);
using (var inStream = new MemoryStream(photoBytes))
{
using (var outStream = new MemoryStream())
{
using (var imageFactory = new ImageFactory())
{
imageFactory.Load(inStream)
.Rotate(new Random().Next(-7, 7))
.RoundedCorners(new RoundedCornerLayer(190))
.Pixelate(3, null)
.Contrast(new Random().Next(-15, 15))
.Brightness(new Random().Next(-15, 15))
.Quality(quality)
.Save(outStream);
}
return outStream;
}
}
}
public void StartUniq()
{
var files = Directory.GetFiles("mypath");
Parallel.ForEach(files, (picture) => { UniqPicture(picture); });
}
}
当我启动 StartUniq() 方法时,我的 CPU 绑定到 12-13% 并且没有更多。我可以使用更多的 CPU % 来执行此操作吗?为什么不增加?
我尝试用 python 来做,也只有 12-13%。它是酷睿 i7 8700。
让它运行得更快的唯一方法是启动应用程序的第二个窗口。
这是窗口限制?使用 Windows Server 2016。
我认为这是系统限制,因为如果我尝试这个简单的代码,它也会绑定 12% 的 CPU!
while (true)
{
var a = 1 + 2;
}
【问题讨论】:
-
为什么你认为使用更多的 CPU 会使其运行得更快?您的 CPU 有 6 个内核,看起来像 100/6 => 16,所以它可能使用了一个内核(它没有针对多核处理进行优化)。如果您无法修改它以使其成为多线程,请并行处理更多文件。如果你只有一个文件要处理,那你可能就不走运了
-
我的猜测是,您可能是磁盘 IO 受限,或者您从 ImageFactory 使用的库可能是写成单线程的。
-
我会根据图像处理来衡量文件 I/O。其中一个可能比另一个更快。只有有了这些结果,我才会考虑如何优化。
-
我必须尝试启动它来创建新任务、新线程。还尝试为每张图像创建任务,没有一种方法可以帮助。
-
您是否尝试将 Thread.CurrentThread 的 Priority Property 增加到最高,或者
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime(危险)?
标签: c# windows multithreading concurrency cpu