我希望能够计算出我的软件执行查找的速率。该软件正在迭代listbox
,其中包含用户名,然后查询我的服务器。我想计算每秒钟我有多少用户名查找?
我是否必须使用每1000米/秒执行计算的计时器?我真的不知道从哪里开始。
我没有任何代码可以显示,只是想得到一些伪代码。
答案 0 :(得分:4)
这可能会有所帮助(我真的不知道delphi,因此无法验证语法,它只是每个请求的伪代码):
var
// Set a timer and counter variable
timer : TDateTime;
rate, counter : Integer;
n : Integer; // Iterator
begin
timer := Time;
counter := 0;
for n := 0 to list.items.count - 1 do
begin
// Do the processing here
// add 1 to the counter every time you iterate over a username
counter := counter + 1;
end;
// Divide Time difference by total to get the rate of username lookups per second
// TDateTime is counted in days, convert it to seconds, to get "per sec" rate
rate := counter / ((Time - timer) * 24 * 60 * 60);
答案 1 :(得分:0)
如果你想看到你的程序每秒执行大量的锁定,你可以用TTimer做到这一点。
首先,您需要在循环中设置soume计数器来计算已处理的项目数:
for n := 0 to list.items.count - 1 do
begin
// Do the processing here
// add 1 to the counter every time you iterate over a username
counter := counter + 1;
end;
然后在Timer的OnTimer事件中检查当前计数器状态并输出要标记的状态。最后你将你的计数器重置为零:
procedure TForm1.Timer1Timer(Sender: TObject);
begin
//read the coutner value to find out how many items was processed
Label1.Caption := IntToStr(Counter);
//reset timer to zero
Counter := 0;
end;
现在,这将为您提供在最后一秒处理了多少项的近似结果。为什么只是近似? TTimer是基于Windows消息的组件。这意味着它不会保证精度,因此OnTimer事件可能不会在指定的时间间隔内完全触发。我看到偏差甚至高达半秒钟。它很大程度上取决于您的主程序代码和整个系统利用率。
注意:如果您在主程序线程中执行所有这些处理,这种方法将无法工作,因为此类处理可能会锁定您的应用程序,直到循环结束。这意味着您的应用程序不会处理任何基于Windows的消息,包括为了触发定时器OnTimer事件而创建的消息。
在这种情况下,我推荐下一个方法。而不是在一秒钟内测量处理的项目数量,而不是测量处理X项目数量所需的时间。 你可以这样做:
const X := 20; //Constant defining how many items needs to be processed
//before processing time is evaluated
//You will need to find out which number of items is best
//suitable for you on your own by trial and error.
var
//StopWatch is a special record which alows precision timing
sw: TStopWatch;;
//Variable for storing elapsed milliseconds of one measuring cycle
elapsedMilliseconds : cardinal;
//Estimated number of calculations that would have been processed in one
//second
CalculationsPerSecond: Integer;
begin
counter := 0;
//Initialize the stop watch
sw := TStopWatch.Create() ;
//Start stopwatch
sw.Start;
for n := 0 to list.items.count - 1 do
begin
// Do the processing here
// add 1 to the counter every time you iterate over a username
counter := counter + 1;
//Check if the counter has been set to specific number of cycles
//you want to to measure time taken for
if Counter = X then
begin
//Stop the StopWatch
sw.Stop;
//Get how many milliseconds have elapsed since start
elapsedMilliseconds := sw.ElapsedMilliseconds;
//Calculate estimated number of items that would have been processed
//per second
CalculationsPerSecond := Round(1000 * X / elapsedMillisecond);
//Reset counter to zero fopr next cycle
counter := 0;
//Reset stopwatch to zero for next cycle
sw.Reset;
//Start stopwatch agina for next cycle
sw.Start;
end;
//Stop the StopWatch since we no longer need it
sw.Stop;
//Free up the stopwatch record to free up the used memory
sw.Free;
end;