本地编译并运行文件,测试运行时间并判断运行结果

本文介绍了一个用于ACM竞赛中测试程序正确性的C语言脚本。该脚本包括源代码编译、运行时间统计及输出结果对比等功能,确保代码符合比赛要求。

需求是这样的:在正式加ACM试题之前,首先要进行测试,比如代码运行时间测试,输出结果的正确性等,一切都正常才能添加到比赛中。

这个程序实现的功能也比较简单:

1.对源代码进行编译

2.运行编译生成的文件,计算程序的运行时间

3. 比较输出结果和标准输出是否相同

/*************************************************************************
    > File Name: 本地测试代码.c
    > Author: ma6174
    > Mail: ma6174@163.com 
    > Created Time: 2012年02月24日 星期五 16时39分46秒
 ***********************************************************************
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/time.h>
#include<time.h>
void compile()
{
    char solution[1000];
    char compiler[1000]="g++ -o temp_sol ";
    printf("请输入源码文件:\n");
    gets(solution);
    int i,len_sol=strlen(solution);
    for(i=0;i<len_sol-1;i++)
    {
        compiler[16+i]=solution[i];
    }
    system(compiler);
}
void count_time()
{
    char run[1000]="./temp_sol < ";
    char input_file[1000];
    printf("请输入input数据文件:\n");
    gets(input_file);
    int i,len_input_file=strlen(input_file);
    for(i=0;i<len_input_file;i++)
    {
        run[13+i]=input_file[i];
    }
    strcat(run," > /tmp/acm_test/output");
    struct timeval tv_start,tv_end;
    gettimeofday(&tv_start,NULL);
    system(run);
    gettimeofday(&tv_end,NULL);
    printf("程序运行时间为:%lf秒\n",tv_end.tv_sec-tv_start.tv_sec+(tv_end.tv_usec-tv_start.tv_usec)/1000000.0);
}
int compare()
{
    printf("请输入标准输出文件:\n");
    char output[1000];
    gets(output);
    char diff[1000]="cmp -s ";
    strcat(diff,"/tmp/acm_test/output ");
    strcat(diff,output);
    int status=system(diff);
    if(fopen("/tmp/acm_test/output","rt")==NULL)
    {
        printf("文件读取错误!\n");
        return -1;
    }
    if(status==0)
    {
        printf("输出完全相同\n");
    }
    else
    {
        printf("输出不相同\n");
    }

}
int main()
{
    compile();
    count_time();
    compare();

}

收获:

这个程序是在linux环境下写的,也是在linux下用的,所以有些功能实现起来和windows不太一样,比如测试时间函数。

我以前发表过一篇博客讨论关于统计程序运行时间的问题,那是在windows下的,在linux下是这样统计的:

struct timeval tv_start,tv_end;
gettimeofday(&tv_start,NULL);
system(run);
gettimeofday(&tv_end,NULL);
printf("程序运行时间为:%lf秒\n",tv_end.tv_sec-tv_start.tv_sec+(tv_end.tv_usec-tv_start.tv_usec)/1000000.0);

其中timeval的结构体定义是这样的:

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds 微秒=1/10^6秒 */

}; 

还有就是system()函数调用系统命令是有返回值的,有时候可以根据返回值判断执行结果!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值