下面的代码在一个 NSOperationQueue 中添加了多个 NSOperation 实例。Operation 只获取 url 的内容。我也提供了php代码...
鉴于以下代码...
-(void)requestResponse {
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.someurl.gr/test.php"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:40.0];
NSDate *dd = [NSDate date];
NSURLResponse *resp;
NSData *returnedData = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:NULL];
NSString *ss = [[[NSString alloc] initWithData:returnedData encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"%@ - %.2f",ss , -[dd timeIntervalSinceNow]);
}
-(NSOperation*)task {
NSInvocationOperation* theOp = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(requestResponse) object:nil] autorelease];
return theOp;
}
-(IBAction)buttonAction:(id)sender {
NSOperationQueue *opq = [[NSOperationQueue alloc] init];
[opq setMaxConcurrentOperationCount:40];
for(int i=0; i<15;i++) {
[opq addOperation:[self task]];
[NSThread sleepForTimeInterval:1.0]; // here is the issue!
}
[opq release];
}
test.php 女巫 -requestResponse 调用的内容:
<?php
echo "Through!";
for($i=0;$i<1000000;$i++) { // don't return too soon
}
?>
问题是,当我[NSThread sleepForTimeInterval:1.0]
在队列中添加每个 NSOperation 之前创建延迟时,所有请求都需要大约相同的时间才能完成。如果我评论这一行,大多数请求需要越来越多的时间才能完成。问题是为什么?
我已经从命令行(使用curl)测试了url,并且请求需要相同的时间来完成对php的任意数量的同时调用,所以问题不在于服务器端。
这是使用 localhost 作为服务器并禁用 sleepForTimeInterval的输出
[s] Through! - 0.22
[s] Through! - 0.23
[s] Through! - 0.25
[s] Through! - 0.26
[s] Through! - 0.26
[s] Through! - 0.28
[s] Through! - 0.43
[s] Through! - 0.46
[s] Through! - 0.49
[s] Through! - 0.50
[s] Through! - 0.52
[s] Through! - 0.51
[s] Through! - 0.60
[s] Through! - 0.62
[s] Through! - 0.63
// 当然,差异更大(从 7 到 20 秒!)用 php 做一些实际的工作。
并启用 sleepForTimeInterval
[s] Through! - 0.23
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.08
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.08
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09
[s] Through! - 0.09