poo*_*kie 0 c# c++ performance for-loop
对于踢,我想看看C#for-loop的速度与C++ for循环的速度相比如何.我的测试是简单地遍历for循环100000次,100000次,并对结果取平均值.
这是我的C#实现:
static void Main(string[] args) {
var numberOfMeasurements = 100000;
var numberOfLoops = 100000;
var measurements = new List < long > ();
var stopwatch = new Stopwatch();
for (var i = 0; i < numberOfMeasurements; i++) {
stopwatch.Start();
for (int j = 0; j < numberOfLoops; j++) {}
measurements.Add(stopwatch.ElapsedMilliseconds);
}
Console.WriteLine("Average runtime = " + measurements.Average() + " ms.");
Console.Read();
}
Run Code Online (Sandbox Code Playgroud)
结果: Average runtime = 10301.92929 ms.
这是我的C++实现:
void TestA()
{
auto numberOfMeasurements = 100000;
auto numberOfLoops = 100000;
std::vector<long> measurements;
for (size_t i = 0; i < numberOfMeasurements; i++)
{
auto start = clock();
for (size_t j = 0; j < numberOfLoops; j++){}
auto duration = start - clock();
measurements.push_back(duration);
}
long avg = std::accumulate(measurements.begin(), measurements.end(), 0.0) / measurements.size();
std::cout << "TestB: Time taken in milliseconds: " << avg << std::endl;
}
int main()
{
TestA();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果: TestA: Time taken in milliseconds: 0
当我看到里面的东西时measurements,我注意到它充满了零......所以,它是什么,这里有什么问题?是clock吗?有没有更好/正确的方法来测量for循环?