Divide work, assign task to an array of threads

做~自己de王妃 提交于 2019-12-24 10:48:12

问题


I need to do math calculations for a text in a memo. [Size of the file: ~2mb]

A fitting example would be an encoded text that I need to decode.

I pass the memo text to a string in order to decode it. I guess it would be way faster to run my decode function using threads. But after some googling I didn't find a good example fitting my purpose.

Example function:

function entr_base_N(my_text:String):String;
var
    ts_hamil64:Integer;
begin
    For ts_hamil64 := 1 to Length(my_text) do
    begin
         Result:= Result + Chr(Ord(my_text[ts_hamil64])+10)
    end;    
end;
.....
.....
Memo1.Text:=entr_base_N(Memo1.Text)

I would like to break the work into small pieces, divide the job equally, lets say 3..8 threads and assign my decode function to those threads. Can you please guide me on this?

Current time to process the text file: ~35seconds. Thank you for your kind help.


回答1:


Threading is not the problem. Your function entr_base_N runs instantly. Try inside the debugger. You'll find it takes no time at all. Processing a 2MB string is trivial on a modern computer. That said, I would always recommend pre-allocating a return buffer when possible.

All the time is spent sending the resulting string back to the memo control. What is happening is that you are converting the #13 and #10 characters to #23 and #20. For whatever reason, the memo control does not like that. It seems to me that you are sending back a string with no line feeds at all and the memo's word wrap code performs badly.

A quick and dirty way to see that this is so is to set WordWrap to False on your memo.

The important lesson here is that you must correctly identify the bottleneck before attempting to optimise. It's an easy trap to fall into though, as my initial fumbled efforts to answer this question demonstrate.




回答2:


To make the assignment to Memo1.Text faster, you can use the following:

memo1.Perform(wm_setredraw, 0, 0);
try
  memo1.Text:= entr_base_N(memo1.Text);
finally
  memo1.Perform(wm_setredraw, 1, 0);
  memo1.invalidate;
end;


来源:https://stackoverflow.com/questions/11352059/divide-work-assign-task-to-an-array-of-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!