一个很有意思的测试

本文通过在不同编程环境中执行相同计时任务的方式,对比了Visual C++, Java, C#, 和 MATLAB等平台上的循环计时差异。每个实验都运行了多次以确保结果的可靠性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

平台:Visual C++6.0

#include "stdafx.h"
#include 
<time.h>
#include 
<stdio.h>
int main(int argc, char* argv[])
{
    
for ( int cnt=0; cnt < 1000000; cnt++ )
    
{
        time_t start;
        time(
&start);

        
for ( int i = 0; i < 1; i++ )
            ;
        
        time_t end;
        time(
&end);
        
if( end > start)
            printf(
"%d",end-start);
        
    }

    
return 0;
}

 运行五次

0
11
1
1
0

将循环次数改为10000000,运行五次,结果分别为:

 1111111
11111
11111111111
111111111
11111111

 

平台:Eclipse3.2 ,JDK1.5

public class Test implements Runnable
{
    
public static void main(String[] args)
    
{
        Thread tThread 
= new Thread(new Test());
        tThread.setPriority(Thread.MAX_PRIORITY);
        tThread.start();
    }

    
public void run()
    
{
        
int cnt = 1;
        
long MAX_VALUE = 1000000;
        
while( cnt < MAX_VALUE )
        
{
            
long start = System.currentTimeMillis();
            
for ( int i = 0; i < 1; i++ )
                ;
            
long end = System.currentTimeMillis();
            
if( end > start )
                System.out.print((end-start)+"/t");

            cnt
++;
        
//    System.gc();
        }

    }

}

运行五次,结果依次为:

16    15    15    16    15    16    
16    15    16    15    16    16
16    15    15    15
15    16    16    15    16
15    16    15    15    16    15

倘若 循环最末端 加上 System.gc(); ,整个代码段运行时间会大大增加(10倍以上),但输出可能性大大减少。

注意,这里用了线程,且是最高优先级。但用普通优先级与最高优先级获得的效果似乎一样的。

 

 

平台:Visual Studio 2005,  C#

using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;

namespace TestApplication
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            test();
        }

        
public static void test()
        
{
            
int cnt = 0;
            
int cc = 0;
            
while (cnt < 1000000)
            
{
                
int startTime = DateTime.Now.Millisecond;

                
for (int i = 0; i < 1; i++)
                    ;
                
int endTime = DateTime.Now.Millisecond;

                
if (endTime > startTime)
                    cc
++;
                   
// Console.Write( (endTime - startTime)+" " );

                cnt
++;
            }

            Console.WriteLine(cc);
        }

    }

}

由于输出量太大了,所以没办法一个个写出来,只好计数。运行五次,计数如下:

48
43
34
46
40

 

 平台Matlab:

= 0;
for i = 1:1000000
    tic
    for i 
= 1:1
        
;
    end
    ct
=toc;
    if( ct>0 )
        n 
= n+1;
    end
end
n
    

输出量太大,因此改为计数,运行五次,计数如下:

240
227
210
215
225

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值