先来个1亿的次的循环,在执行for和while循环之前打印一下时间,然后相减来得出结论。
代码如下
#include <stdio.h>
#include <sys/time.h>
static void TestFor(void)
{
int i = 0;
// 获取当前的毫秒值
struct timeval tv, ev;
gettimeofday(&tv, NULL);
for (; i < 100000000; i++)
{
}
gettimeofday(&ev, NULL);
// 获取执行前和执行后的相差值
printf("---------------------------> For: \r\n");
printf("Begin: %ldus \r\n", tv.tv_usec);
printf("End: %ldus \r\n", ev.tv_usec);
printf("Dif: %ldus \r\n", ev.tv_usec - tv.tv_usec);
}
static void TestWhile(void)
{
int i = 0;
// 获取当前的毫秒值
struct timeval tv, ev;
gettimeofday(&tv, NULL);
while (i++ < 100000000)
{
}
gettimeofday(&ev, NULL);
// 获取执行前和执行后的相差值
printf("---------------------------> While: \r\n");
printf("Begin: %ldus \r\n", tv.tv_usec);
printf("End: %ldus \r\n", ev.tv_usec);
printf("Dif: %ldus \r\n", ev.tv_usec - tv.tv_usec);
}
int main()
{
TestFor();
TestFor();
TestWhile();
TestWhile();
return 0;
}
输出如下。 由此可见,在什么事情都不做的情况下,while循环快。
---------------------------> For:
Begin: 150277us
End: 177275us
Dif: 26998us
---------------------------> For:
Begin: 178277us
End: 206275us
Dif: 27998us
---------------------------> While:
Begin: 207277us
End: 223277us
Dif: 16000us
---------------------------> While:
Begin: 224276us
End: 241275us
Dif: 16999us
接下来我们做点事情,随便来个变量++。
/*
* @Author: Troubadour 2276791354@qq.com
* @Date: 2024-04-16 10:45:12
* @LastEditors: Troubadour 2276791354@qq.com
* @LastEditTime: 2024-04-16 10:57:03
* @Version:
* @Description:
*/
#include <stdio.h>
#include <sys/time.h>
static void TestFor(void)
{
int i = 0;
int Cnt = 0;
// 获取当前的毫秒值
struct timeval tv, ev;
gettimeofday(&tv, NULL);
for (; i < 100000000; i++)
{
Cnt++;
}
gettimeofday(&ev, NULL);
// 获取执行前和执行后的相差值
printf("---------------------------> For: \r\n");
printf("Begin: %ldus \r\n", tv.tv_usec);
printf("End: %ldus \r\n", ev.tv_usec);
printf("Dif: %ldus \r\n", ev.tv_usec - tv.tv_usec);
}
static void TestWhile(void)
{
int i = 0;
int Cnt = 0;
// 获取当前的毫秒值
struct timeval tv, ev;
gettimeofday(&tv, NULL);
while (i++ < 100000000)
{
Cnt++;
}
gettimeofday(&ev, NULL);
// 获取执行前和执行后的相差值
printf("---------------------------> While: \r\n");
printf("Begin: %ldus \r\n", tv.tv_usec);
printf("End: %ldus \r\n", ev.tv_usec);
printf("Dif: %ldus \r\n", ev.tv_usec - tv.tv_usec);
}
int main()
{
TestFor();
TestFor();
TestWhile();
TestWhile();
return 0;
}
输出如下。 由此可见,在什么事情都不做的情况下,while略快,但是差距并不明显。
---------------------------> For:
Begin: 56651us
End: 88651us
Dif: 32000us
---------------------------> For:
Begin: 89653us
End: 122651us
Dif: 32998us
---------------------------> While:
Begin: 123674us
End: 154676us
Dif: 31002us
---------------------------> While:
Begin: 155652us
End: 186671us
Dif: 31019us
结论:两个循环实际在使用的情况下,速度差不多。