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

需求是这样的:在正式加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()函数调用系统命令是有返回值的,有时候可以根据返回值判断执行结果!

posted on   ma6174  阅读(839)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库

导航

统计

点击右上角即可分享
微信分享提示